WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Rewrite API/add rewrite tag

Description

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.

Usage

<?php add_rewrite_tag($tag$regex$query); ?>

Arguments

$tag
(string) (required) The tag name you want to use, with a leading and trailing %.
Default: None
$regex
(string) (required) Specify a regex to validate the value of the tag.
Default: None
$query
(string) (optional) Append query to queryreplace property array.
Default: None

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)

Example

The following will register a tag called 'film_title':

<?php
    
function custom_rewrite_tag() {
        
add_rewrite_tag('%film_title%''([^&]+)');
    }
    
add_action('init''custom_rewrite_tag'100);
?>

This is particularly important when you are using rewrites with custom page templates.

Retrieving the Value of a Rewritten URL

With a rewrite tag defined, you can now retrieve the value of your rewritten querystring variables using WordPress's $wp_query variable. To get the value of the above tag out of a rewrite, you could use the following in your page template:

$wp_query->query_vars['film_title']

Note that using $_GET on a rewritten URL will not work, even if the rewrite includes the querystring variables. You must use $wp_query.

Source File

add_rewrite_tag() is located in wp-includes/rewrite.php.

Related

Articles

Hooks

Functions

External Resources