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

Rewrite API/add rewrite tag


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.


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


(string) (required) The tag name you want to use, with a leading and trailing %.
Default: None
(string) (required) Specify a regex to validate the value of the tag.
Default: None
(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)


The following will register a tag called 'film_title':

function custom_rewrite_tag() {

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:


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.





External Resources