add_rewrite_tag

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

Description

add_rewrite_tag( (string) $tag, (string) $regex, (string) $query = '' ); 

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.

Parameters (3)

0. $tag (string)
Name of the new rewrite tag.
1. $regex (string)
Regular expression to substitute the tag for in rewrite rules.
2. $query — Optional. (string) => ''
String to append to the rewritten query. Must end in =.. Default empty.

Usage

  1. if ( !function_exists( 'add_rewrite_tag' ) ) { 
  2. require_once ABSPATH . WPINC . '/rewrite.php'; 
  3.  
  4. // Name of the new rewrite tag. 
  5. $tag = ''; 
  6.  
  7. // Regular expression to substitute the tag for in rewrite rules. 
  8. $regex = ''; 
  9.  
  10. // Optional. String to append to the rewritten query. Must end in '='. Default empty. 
  11. $query = ''; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = add_rewrite_tag($tag, $regex, $query); 
  15.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/rewrite.php  
  1. function add_rewrite_tag( $tag, $regex, $query = '' ) { 
  2. // validate the tag's name 
  3. if ( strlen( $tag ) < 3 || $tag[0] != '%' || $tag[ strlen($tag) - 1 ] != '%' ) 
  4. return; 
  5.  
  6. global $wp_rewrite, $wp; 
  7.  
  8. if ( empty( $query ) ) { 
  9. $qv = trim( $tag, '%' ); 
  10. $wp->add_query_var( $qv ); 
  11. $query = $qv . '='; 
  12.  
  13. $wp_rewrite->add_rewrite_tag( $tag, $regex, $query );