The add_rewrite_tag() WordPress PHP function adds a new rewrite tag (like %postname%) to WordPress URL structure. This function is used when you want to add custom data in the URL of your WordPress site.
Usage
To use add_rewrite_tag(), you should call it within an ‘init’ hook. Here’s a basic example:
add_action('init', 'add_my_rewrites');
function add_my_rewrites() {
add_rewrite_tag('%mytag%', '([^&]+)', 'mytag=');
}
In this example, %mytag% is the new rewrite tag we’re adding, '([^&]+)' is the regular expression that will match our new tag, and 'mytag=' is the query variable WordPress will use for this tag.
Parameters
- $tag (string): This is the name of the new rewrite tag. It should be in the format
%tagname%. - $regex (string): This is the regular expression that matches your tag in rewrite rules.
- $query (string): This is optional. It’s the string to append to the rewritten query and it must end with ‘=’. The default value is empty string.
More information
See WordPress Developer Resources: add_rewrite_tag()
This function is part of the Rewrite API and was implemented in WordPress 2.1.
Examples
Custom Taxonomy Location Tag
In this example, we’re assuming the site has a custom taxonomy ‘location’ with terms like “Paris” or “Madrid”. We add a rewrite tag %location% to establish the location query var.
add_action('init', 'add_my_rewrites');
function add_my_rewrites() {
add_rewrite_tag('%location%', '([^&]+)', 'location=');
add_rewrite_rule('^goto/([^/]*)/([^/]*)/?','index.php?location=$matches[1]&name=$matches[2]','top');
}
Assign Value to %location% Tag
To make the %location% tag behave like a structure tag, use the post_link filter to replace the tag with the proper term.
// Assign value to %location% rewrite tag
add_filter('post_link', 'my_filter_post_link', 10, 2 );
function my_filter_post_link( $permalink, $post ) {
// bail if %location% tag is not present in the url:
if ( false === strpos( $permalink, '%location%' ) ) {
return $permalink;
}
$terms = wp_get_post_terms( $post->ID, 'location' );
// set location, if no location is found, provide a default value.
if ( 0 < count( $terms ) ) {
$location = $terms[0]->slug;
} else {
$location = 'timbuktu';
}
$location = urlencode( $location );
$permalink = str_replace('%location%', $location , $permalink );
return $permalink;
}
Register a Tag Called film_title
You can register a tag like %film_title%.
function custom_rewrite_tag() {
add_rewrite_tag('%film_title%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);
Retrieving the Value of a Rewritten URL
You can retrieve the value of your rewritten querystring variables using WordPress’s $wp_query variable.