3 * WordPress Rewrite API
10 * Endpoint Mask for default, which is nothing.
17 * Endpoint Mask for Permalink.
21 define('EP_PERMALINK', 1);
24 * Endpoint Mask for Attachment.
28 define('EP_ATTACHMENT', 2);
31 * Endpoint Mask for date.
38 * Endpoint Mask for year
45 * Endpoint Mask for month.
49 define('EP_MONTH', 16);
52 * Endpoint Mask for day.
59 * Endpoint Mask for root.
63 define('EP_ROOT', 64);
66 * Endpoint Mask for comments.
70 define('EP_COMMENTS', 128);
73 * Endpoint Mask for searches.
77 define('EP_SEARCH', 256);
80 * Endpoint Mask for categories.
84 define('EP_CATEGORIES', 512);
87 * Endpoint Mask for tags.
91 define('EP_TAGS', 1024);
94 * Endpoint Mask for authors.
98 define('EP_AUTHORS', 2048);
101 * Endpoint Mask for pages.
105 define('EP_PAGES', 4096);
108 * Endpoint Mask for all archive views.
112 define( 'EP_ALL_ARCHIVES', EP_DATE | EP_YEAR | EP_MONTH | EP_DAY | EP_CATEGORIES | EP_TAGS | EP_AUTHORS );
115 * Endpoint Mask for everything.
119 define( 'EP_ALL', EP_PERMALINK | EP_ATTACHMENT | EP_ROOT | EP_COMMENTS | EP_SEARCH | EP_PAGES | EP_ALL_ARCHIVES );
122 * Adds a rewrite rule that transforms a URL structure to a set of query vars.
124 * Any value in the $after parameter that isn't 'bottom' will result in the rule
125 * being placed at the top of the rewrite rules.
128 * @since 4.4.0 Array support was added to the `$query` parameter.
130 * @global WP_Rewrite $wp_rewrite WordPress Rewrite Component.
132 * @param string $regex Regular expression to match request against.
133 * @param string|array $query The corresponding query vars for this rewrite rule.
134 * @param string $after Optional. Priority of the new rule. Accepts 'top'
135 * or 'bottom'. Default 'bottom'.
137 function add_rewrite_rule( $regex, $query, $after = 'bottom' ) {
140 $wp_rewrite->add_rule( $regex, $query, $after );
144 * Add a new rewrite tag (like %postname%).
146 * The $query parameter is optional. If it is omitted you must ensure that
147 * you call this on, or before, the 'init' hook. This is because $query defaults
148 * to "$tag=", and for this to work a new query var has to be added.
152 * @global WP_Rewrite $wp_rewrite
155 * @param string $tag Name of the new rewrite tag.
156 * @param string $regex Regular expression to substitute the tag for in rewrite rules.
157 * @param string $query Optional. String to append to the rewritten query. Must end in '='. Default empty.
159 function add_rewrite_tag( $tag, $regex, $query = '' ) {
160 // validate the tag's name
161 if ( strlen( $tag ) < 3 || $tag[0] != '%' || $tag[ strlen($tag) - 1 ] != '%' )
164 global $wp_rewrite, $wp;
166 if ( empty( $query ) ) {
167 $qv = trim( $tag, '%' );
168 $wp->add_query_var( $qv );
172 $wp_rewrite->add_rewrite_tag( $tag, $regex, $query );
176 * Add permalink structure.
180 * @see WP_Rewrite::add_permastruct()
181 * @global WP_Rewrite $wp_rewrite
183 * @param string $name Name for permalink structure.
184 * @param string $struct Permalink structure.
185 * @param array $args Optional. Arguments for building the rules from the permalink structure,
186 * see WP_Rewrite::add_permastruct() for full details. Default empty array.
188 function add_permastruct( $name, $struct, $args = array() ) {
191 // backwards compatibility for the old parameters: $with_front and $ep_mask
192 if ( ! is_array( $args ) )
193 $args = array( 'with_front' => $args );
194 if ( func_num_args() == 4 )
195 $args['ep_mask'] = func_get_arg( 3 );
197 $wp_rewrite->add_permastruct( $name, $struct, $args );
201 * Add a new feed type like /atom1/.
205 * @global WP_Rewrite $wp_rewrite
207 * @param string $feedname Feed name.
208 * @param callable $function Callback to run on feed display.
209 * @return string Feed action name.
211 function add_feed( $feedname, $function ) {
214 if ( ! in_array( $feedname, $wp_rewrite->feeds ) ) {
215 $wp_rewrite->feeds[] = $feedname;
218 $hook = 'do_feed_' . $feedname;
220 // Remove default function hook
221 remove_action( $hook, $hook );
223 add_action( $hook, $function, 10, 2 );
229 * Remove rewrite rules and then recreate rewrite rules.
233 * @global WP_Rewrite $wp_rewrite
235 * @param bool $hard Whether to update .htaccess (hard flush) or just update
236 * rewrite_rules transient (soft flush). Default is true (hard).
238 function flush_rewrite_rules( $hard = true ) {
240 $wp_rewrite->flush_rules( $hard );
244 * Add an endpoint, like /trackback/.
246 * Adding an endpoint creates extra rewrite rules for each of the matching
247 * places specified by the provided bitmask. For example:
249 * add_rewrite_endpoint( 'json', EP_PERMALINK | EP_PAGES );
251 * will add a new rewrite rule ending with "json(/(.*))?/?$" for every permastruct
252 * that describes a permalink (post) or page. This is rewritten to "json=$match"
253 * where $match is the part of the URL matched by the endpoint regex (e.g. "foo" in
254 * "[permalink]/json/foo/").
256 * A new query var with the same name as the endpoint will also be created.
258 * When specifying $places ensure that you are using the EP_* constants (or a
259 * combination of them using the bitwise OR operator) as their values are not
260 * guaranteed to remain static (especially `EP_ALL`).
262 * Be sure to flush the rewrite rules - see flush_rewrite_rules() - when your plugin gets
263 * activated and deactivated.
266 * @since 4.3.0 Added support for skipping query var registration by passing `false` to `$query_var`.
268 * @global WP_Rewrite $wp_rewrite
270 * @param string $name Name of the endpoint.
271 * @param int $places Endpoint mask describing the places the endpoint should be added.
272 * @param string|bool $query_var Name of the corresponding query variable. Pass `false` to skip registering a query_var
273 * for this endpoint. Defaults to the value of `$name`.
275 function add_rewrite_endpoint( $name, $places, $query_var = true ) {
277 $wp_rewrite->add_endpoint( $name, $places, $query_var );
281 * Filter the URL base for taxonomies.
283 * To remove any manually prepended /index.php/.
288 * @param string $base The taxonomy base that we're going to filter
291 function _wp_filter_taxonomy_base( $base ) {
292 if ( !empty( $base ) ) {
293 $base = preg_replace( '|^/index\.php/|', '', $base );
294 $base = trim( $base, '/' );
301 * Resolve numeric slugs that collide with date permalinks.
303 * Permalinks of posts with numeric slugs can sometimes look to WP_Query::parse_query()
304 * like a date archive, as when your permalink structure is `/%year%/%postname%/` and
305 * a post with post_name '05' has the URL `/2015/05/`.
307 * This function detects conflicts of this type and resolves them in favor of the
310 * Note that, since 4.3.0, wp_unique_post_slug() prevents the creation of post slugs
311 * that would result in a date archive conflict. The resolution performed in this
312 * function is primarily for legacy content, as well as cases when the admin has changed
313 * the site's permalink structure in a way that introduces URL conflicts.
317 * @param array $query_vars Optional. Query variables for setting up the loop, as determined in
318 * WP::parse_request(). Default empty array.
319 * @return array Returns the original array of query vars, with date/post conflicts resolved.
321 function wp_resolve_numeric_slug_conflicts( $query_vars = array() ) {
322 if ( ! isset( $query_vars['year'] ) && ! isset( $query_vars['monthnum'] ) && ! isset( $query_vars['day'] ) ) {
326 // Identify the 'postname' position in the permastruct array.
327 $permastructs = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
328 $postname_index = array_search( '%postname%', $permastructs );
330 if ( false === $postname_index ) {
335 * A numeric slug could be confused with a year, month, or day, depending on position. To account for
336 * the possibility of post pagination (eg 2015/2 for the second page of a post called '2015'), our
337 * `is_*` checks are generous: check for year-slug clashes when `is_year` *or* `is_month`, and check
338 * for month-slug clashes when `is_month` *or* `is_day`.
341 if ( 0 === $postname_index && ( isset( $query_vars['year'] ) || isset( $query_vars['monthnum'] ) ) ) {
343 } elseif ( '%year%' === $permastructs[ $postname_index - 1 ] && ( isset( $query_vars['monthnum'] ) || isset( $query_vars['day'] ) ) ) {
344 $compare = 'monthnum';
345 } elseif ( '%monthnum%' === $permastructs[ $postname_index - 1 ] && isset( $query_vars['day'] ) ) {
353 // This is the potentially clashing slug.
354 $value = $query_vars[ $compare ];
356 $post = get_page_by_path( $value, OBJECT, 'post' );
357 if ( ! ( $post instanceof WP_Post ) ) {
361 // If the date of the post doesn't match the date specified in the URL, resolve to the date archive.
362 if ( preg_match( '/^([0-9]{4})\-([0-9]{2})/', $post->post_date, $matches ) && isset( $query_vars['year'] ) && ( 'monthnum' === $compare || 'day' === $compare ) ) {
363 // $matches[1] is the year the post was published.
364 if ( intval( $query_vars['year'] ) !== intval( $matches[1] ) ) {
368 // $matches[2] is the month the post was published.
369 if ( 'day' === $compare && isset( $query_vars['monthnum'] ) && intval( $query_vars['monthnum'] ) !== intval( $matches[2] ) ) {
375 * If the located post contains nextpage pagination, then the URL chunk following postname may be
376 * intended as the page number. Verify that it's a valid page before resolving to it.
379 if ( 'year' === $compare && isset( $query_vars['monthnum'] ) ) {
380 $maybe_page = $query_vars['monthnum'];
381 } elseif ( 'monthnum' === $compare && isset( $query_vars['day'] ) ) {
382 $maybe_page = $query_vars['day'];
384 // Bug found in #11694 - 'page' was returning '/4'
385 $maybe_page = (int) trim( $maybe_page, '/' );
387 $post_page_count = substr_count( $post->post_content, '<!--nextpage-->' ) + 1;
389 // If the post doesn't have multiple pages, but a 'page' candidate is found, resolve to the date archive.
390 if ( 1 === $post_page_count && $maybe_page ) {
394 // If the post has multiple pages and the 'page' number isn't valid, resolve to the date archive.
395 if ( $post_page_count > 1 && $maybe_page > $post_page_count ) {
399 // If we've gotten to this point, we have a slug/date clash. First, adjust for nextpage.
400 if ( '' !== $maybe_page ) {
401 $query_vars['page'] = intval( $maybe_page );
404 // Next, unset autodetected date-related query vars.
405 unset( $query_vars['year'] );
406 unset( $query_vars['monthnum'] );
407 unset( $query_vars['day'] );
409 // Then, set the identified post.
410 $query_vars['name'] = $post->post_name;
412 // Finally, return the modified query vars.
417 * Examine a url and try to determine the post ID it represents.
419 * Checks are supposedly from the hosted site blog.
423 * @global WP_Rewrite $wp_rewrite
426 * @param string $url Permalink to check.
427 * @return int Post ID, or 0 on failure.
429 function url_to_postid( $url ) {
433 * Filter the URL to derive the post ID from.
437 * @param string $url The URL to derive the post ID from.
439 $url = apply_filters( 'url_to_postid', $url );
441 // First, check to see if there is a 'p=N' or 'page_id=N' to match against
442 if ( preg_match('#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values) ) {
443 $id = absint($values[2]);
448 // Check to see if we are using rewrite rules
449 $rewrite = $wp_rewrite->wp_rewrite_rules();
451 // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
452 if ( empty($rewrite) )
455 // Get rid of the #anchor
456 $url_split = explode('#', $url);
457 $url = $url_split[0];
459 // Get rid of URL ?query=string
460 $url_split = explode('?', $url);
461 $url = $url_split[0];
463 // Set the correct URL scheme.
464 $url = set_url_scheme( $url );
466 // Add 'www.' if it is absent and should be there
467 if ( false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.') )
468 $url = str_replace('://', '://www.', $url);
470 // Strip 'www.' if it is present and shouldn't be
471 if ( false === strpos(home_url(), '://www.') )
472 $url = str_replace('://www.', '://', $url);
474 // Strip 'index.php/' if we're not using path info permalinks
475 if ( !$wp_rewrite->using_index_permalinks() )
476 $url = str_replace( $wp_rewrite->index . '/', '', $url );
478 if ( false !== strpos( trailingslashit( $url ), home_url( '/' ) ) ) {
479 // Chop off http://domain.com/[path]
480 $url = str_replace(home_url(), '', $url);
482 // Chop off /path/to/blog
483 $home_path = parse_url( home_url( '/' ) );
484 $home_path = isset( $home_path['path'] ) ? $home_path['path'] : '' ;
485 $url = preg_replace( sprintf( '#^%s#', preg_quote( $home_path ) ), '', trailingslashit( $url ) );
488 // Trim leading and lagging slashes
489 $url = trim($url, '/');
492 $post_type_query_vars = array();
494 foreach ( get_post_types( array() , 'objects' ) as $post_type => $t ) {
495 if ( ! empty( $t->query_var ) )
496 $post_type_query_vars[ $t->query_var ] = $post_type;
500 $request_match = $request;
501 foreach ( (array)$rewrite as $match => $query) {
503 // If the requesting file is the anchor of the match, prepend it
505 if ( !empty($url) && ($url != $request) && (strpos($match, $url) === 0) )
506 $request_match = $url . '/' . $request;
508 if ( preg_match("#^$match#", $request_match, $matches) ) {
510 if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
511 // This is a verbose page match, let's check to be sure about it.
512 $page = get_page_by_path( $matches[ $varmatch[1] ] );
517 $post_status_obj = get_post_status_object( $page->post_status );
518 if ( ! $post_status_obj->public && ! $post_status_obj->protected
519 && ! $post_status_obj->private && $post_status_obj->exclude_from_search ) {
525 // Trim the query of everything up to the '?'.
526 $query = preg_replace("!^.+\?!", '', $query);
528 // Substitute the substring matches into the query.
529 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
531 // Filter out non-public query vars
533 parse_str( $query, $query_vars );
535 foreach ( (array) $query_vars as $key => $value ) {
536 if ( in_array( $key, $wp->public_query_vars ) ){
537 $query[$key] = $value;
538 if ( isset( $post_type_query_vars[$key] ) ) {
539 $query['post_type'] = $post_type_query_vars[$key];
540 $query['name'] = $value;
545 // Resolve conflicts between posts with numeric slugs and date archive queries.
546 $query = wp_resolve_numeric_slug_conflicts( $query );
549 $query = new WP_Query( $query );
550 if ( ! empty( $query->posts ) && $query->is_singular )
551 return $query->post->ID;