add_rewrite_tag()WP 2.1.0

Adds/updates a query tag (for example: '%pagetype%') that can be used in pretty permalinks. This tag will be replaced with a regular expression, which is then used in a query string like: ?pagetype=mypage.

Typically this function is used together with add_rewrite_rule(), which creates a new rewrite rule for pretty permalinks. Often used in WordPress for static pages with a separate template.

If a query variable is registered that already exists in WordPress, the previous variable will be overwritten.

Important: the function should be called on the action init or earlier.

See the list of reserved names for query variables.

No Hooks.

Returns

null. Does not return anything.

Usage

add_rewrite_tag( $tagname, $regex );
$tagname(string) (required)
The name of the variable that will be used as a query variable. The name must be wrapped in %. For example, pagetype is specified as %pagetype%.
$regex(string) (required)
The part of the regular expression that the value of $tagname should match. The expression is wrapped in parentheses. For example, if the query variable is: ?pagetype=pages, you need to describe pages with the regex: ([^&]+)
$query(string)
The query string that will be appended to the end of the query must end with =. For example: post_type=book&name=. As a result, in the rewrite rule, after the = the match element corresponding to the $regex parameter will be set (for example $matches[1])
Default: ''

Examples

1

#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:

get_query_var('pagetype');

or

global $wp_query;
$wp_query->query_vars['pagetype'];

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

Notes

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

Changelog

Since 2.1.0 Introduced.

add_rewrite_tag() code WP 6.9.1

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

	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 );
}