WordPress.org

Ready to get started?Download WordPress

Codex

Rewrite API/add rewrite tag

Contents

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

add_rewrite_tag($tagname,$regex,$query);

Arguments

$tagname
The tag name you want to use, with a leading and trailing %.
$regex
Specify a regex to validate the value of the tag.
$query
Append query to queryreplace property array.

What it does

  • Gets a query var name by stripping the % signs from the name of the tag: trim($name, '%')
  • 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':

add_rewrite_tag('%film_title%','([^&]+)');

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