Prefixes the given URL path pattern with the base path for the given context.
Description
This ensures that these path patterns work correctly on WordPress subdirectory sites, for example in a multisite network, or when WordPress itself is installed in a subdirectory of the hostname.
The given URL path pattern is only prefixed if it does not already include the expected prefix.
Parameters
$path_pattern
stringrequired- URL pattern starting with the path segment.
$context
stringoptional- Context to use for prefixing the path pattern. Default
'home'
.Default:
'home'
Source
public function prefix_path_pattern( string $path_pattern, string $context = 'home' ): string {
// If context path does not exist, the context is invalid.
if ( ! isset( $this->contexts[ $context ] ) ) {
_doing_it_wrong(
__FUNCTION__,
esc_html(
sprintf(
/* translators: %s: context string */
__( 'Invalid URL pattern context %s.' ),
$context
)
),
'6.8.0'
);
return $path_pattern;
}
/*
* In the event that the context path contains a :, ? or # (which can cause the URL pattern parser to switch to
* another state, though only the latter two should be percent encoded anyway), it additionally needs to be
* enclosed in grouping braces. The final forward slash (trailingslashit ensures there is one) affects the
* meaning of the * wildcard, so is left outside the braces.
*/
$context_path = $this->contexts[ $context ];
$escaped_context_path = $context_path;
if ( strcspn( $context_path, ':?#' ) !== strlen( $context_path ) ) {
$escaped_context_path = '{' . substr( $context_path, 0, -1 ) . '}/';
}
/*
* If the path already starts with the context path (including '/'), remove it first
* since it is about to be added back.
*/
if ( str_starts_with( $path_pattern, $context_path ) ) {
$path_pattern = substr( $path_pattern, strlen( $context_path ) );
}
return $escaped_context_path . ltrim( $path_pattern, '/' );
}
Changelog
Version | Description |
---|---|
6.8.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.