add_rewrite_tag( string $tag, string $regex, string $query = '' )
Add a new rewrite tag (like %postname%).
Description Description
The $query parameter is optional. If it is omitted you must ensure that you call this on, or before, the ‘init’ hook. This is because $query defaults to "$tag=", and for this to work a new query var has to be added.
Parameters Parameters
- $tag
-
(string) (Required) Name of the new rewrite tag.
- $regex
-
(string) (Required) Regular expression to substitute the tag for in rewrite rules.
- $query
-
(string) (Optional) String to append to the rewritten query. Must end in '='.
Default value: ''
Source Source
File: wp-includes/rewrite.php
function add_rewrite_tag( $tag, $regex, $query = '' ) { // validate the tag's name if ( strlen( $tag ) < 3 || $tag[0] != '%' || $tag[ strlen( $tag ) - 1 ] != '%' ) { return; } global $wp_rewrite, $wp; if ( empty( $query ) ) { $qv = trim( $tag, '%' ); $wp->add_query_var( $qv ); $query = $qv . '='; } $wp_rewrite->add_rewrite_tag( $tag, $regex, $query ); }
Expand full source code Collapse full source code View on Trac
Changelog Changelog
Version | Description |
---|---|
2.1.0 | Introduced. |
User Contributed Notes User Contributed Notes
You must log in before being able to contribute a note or feedback.
In the following examples, imagine a site has a custom taxonomy ‘location’ and all posts are assigned a location term like “Paris” or “Madrid”. We add a rewrite tag “%location%” to establish the
location
query var. We also add a rewrite rule so that an URL such as example.com/goto/madrid/budget-lodging/ is properly handled.Even though rewrite tags look just like permalink structure tags, if you try to use your rewrite tag in a permalink structure, the URLs generated by WordPress will look something like example.com/goto/%location%/budget-lodging/. The proper term does not replace the rewrite tag as you might expect. To make your tag behave like a structure tag, use the “post_link” filter to replace the tag with the proper term.
Expand full source codeCollapse full source code
Anytime you change something related to the Rewrite API, don’t forget to flush the rewrite rules! This can be done without code by going to Permalink Settings and clicking Save Changes. You don’t actually need to make any changes on the settings screen.