add_rewrite_tag(): Add Custom URL Rewrite Tags in WordPress

add_rewrite_tag Description

This function adds a custom query string tag. It is generally used together with add_rewrite_rule() when adding custom URL rewrite rules for a custom template.

If you declare a rewrite tag that already exists, the existing tag will be overwritten.

This function must be called on init or earlier.

add_rewrite_tag Usage

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

add_rewrite_tag Parameters

$tag

(string) (required) The name of the rewrite tag. It must begin and end with %.
Default: None

$regex
(string) (required) The regular expression assigned to the tag.
Default: None

$query
(string) (optional) Additional query text added to the query vars array.
Default: None

What add_rewrite_tag() does

  • It gets the query variable name by trimming the % characters: trim($tag, '%').
  • It calls $wp_rewrite->add_rewrite_tag() with the query tag name to register the query variable name and the corresponding regular expression.
  • It adds the query variable to the recognized query vars.

add_rewrite_tag Example

The following code registers a query tag named film_title:

function custom_rewrite_tag() {
    add_rewrite_tag('%film_title%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);

This is especially important when using rewrites with a custom page template.

Get query parameter values after the rewrite

After defining the query tag, we can use WordPress’s $wp_query instance to get the value of the custom query parameter. For example, to retrieve the value of the query tag above, we can get it in the page template like this.

$wp_query->query_vars['film_title']

Note: after a URL has been rewritten, you cannot retrieve the query parameter with $_GET, even if that parameter is included in the rewrite target. To get it, you must use $wp_query.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *