add_rewrite_tag()WP 2.1.0

Add a new rewrite tag (like %postname%).

The $query parameter is optional. If it is omitted you must ensure that you call this on, or before, the init hook. This is because $query defaults to $tag=, and for this to work a new query var has to be added.

No Hooks.


null. Nothing (null).


add_rewrite_tag( $tag, $regex, $query );
$tag(string) (required)
Name of the new rewrite tag.
$regex(string) (required)
Regular expression to substitute the tag for in rewrite rules.
String to append to the rewritten query. Must end in '='.
Default: ''



#1 Registering a new query variable in WP

This example will register a query tag pagetype:

add_action('init', 'rewrite_rule_my');
function rewrite_rule_my(){
	add_rewrite_tag( '%pagetype%', '([^&]+)' );

This procedure is required when rewrite rule is created with function add_rewrite_rule(). Usually such rule is created for static pages with unique template.

Obtaining values

The value of the query variables from overwritten URLs is obtained through $wp_query.

For example, we had a link sitemap?pagetype=pages we specified the rewrite rule and the link became sitemap/pages, now to get the correct value pages to use in PHP and be sure that it refers exactly to the query variable pagetype, in the template we use:



global $wp_query;

It is impossible to get $_GET parameter when Friendly URL is used. That is, when /sitemap/pages $_GET['pagetype'] is empty.


  • Global. WP_Rewrite. $wp_rewrite WordPress rewrite component.
  • Global. WP. $wp Current WordPress environment instance.


Since 2.1.0 Introduced.

add_rewrite_tag() code WP 6.4.3

function add_rewrite_tag( $tag, $regex, $query = '' ) {
	// Validate the tag's name.
	if ( strlen( $tag ) < 3 || '%' !== $tag[0] || '%' !== $tag[ strlen( $tag ) - 1 ] ) {

	global $wp_rewrite, $wp;

	if ( empty( $query ) ) {
		$qv = trim( $tag, '%' );
		$wp->add_query_var( $qv );
		$query = $qv . '=';

	$wp_rewrite->add_rewrite_tag( $tag, $regex, $query );