On this page
add_rewrite_tag( string $tag, string $regex, string $query = '' )
Adds a new rewrite tag (like %postname%).
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
$tagstring Required-
Name of the new rewrite tag.
$regexstring Required-
Regular expression to substitute the tag for in rewrite rules.
$querystring Optional-
String to append to the rewritten query. Must end in
'='.Default:
''
More Information
This function can be used to make WordPress aware of custom querystring variables. Generally, it’s used in combination with add_rewrite_rule() to create rewrite rules for pages with custom templates.
If you use this function to declare a rewrite tag that already exists, the existing tag will be overwritten.
This function must be called on init or earlier.
What it does
- Gets a query var name by stripping the % signs from the name of the tag: trim($tag, ‘%’)
- Calls $wp_rewrite::add_rewrite_tag() with the name, generated QV name and regex.
- Adds the QV as a query var (again, this could be done by filtering query_vars but it might be nicer to add a function to the WP class that stores ‘extra’ QVs like above)
Source
File: wp-includes/rewrite.php. View all references
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 );
}
Related
Uses
| Uses | Description |
|---|---|
| WP::add_query_var() wp-includes/class-wp.php | Adds a query variable to the list of public query variables. |
| WP_Rewrite::add_rewrite_tag() wp-includes/class-wp-rewrite.php | Adds or updates existing rewrite tags (e.g. %postname%). |
Used By
| Used By | Description |
|---|---|
| WP_Sitemaps::register_rewrites() wp-includes/sitemaps/class-wp-sitemaps.php | Registers sitemap rewrite tags and routing rules. |
| WP_Taxonomy::add_rewrite_rules() wp-includes/class-wp-taxonomy.php | Adds the necessary rewrite rules for the taxonomy. |
| WP_Post_Type::add_rewrite_rules() wp-includes/class-wp-post-type.php | Adds the necessary rewrite rules for the post type. |
Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |
© 2003–2022 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/functions/add_rewrite_tag