add_rewrite_tag()
云策文档标注
概述
add_rewrite_tag() 函数用于向 WordPress 添加新的重写标签(如 %postname%),使 WordPress 能够识别自定义查询字符串变量。它通常与 add_rewrite_rule() 结合使用,为自定义模板页面创建重写规则。
关键要点
- 添加新重写标签,参数包括标签名、正则表达式和可选的查询字符串。
- 必须在 init 钩子或之前调用,否则需提供 $query 参数以避免默认行为问题。
- 如果标签已存在,将被覆盖;函数内部会生成查询变量名并调用 WP_Rewrite::add_rewrite_tag()。
- 常用于自定义分类法或页面模板,需注意重写规则刷新(如保存固定链接设置)。
代码示例
add_action('init', 'add_my_rewrites');
function add_my_rewrites() {
add_rewrite_tag('%location%', '([^&]+)', 'location=');
add_rewrite_rule('^goto/([^/]*)/([^/]*)/?','index.php?location=$matches[1]&name=$matches[2]','top');
}注意事项
- 重写标签不能直接在固定链接结构中替换,需使用 post_link 过滤器处理。
- 重写后,查询变量值应通过 $wp_query->query_vars 获取,而非 $_GET。
- 修改重写 API 相关设置后,务必刷新重写规则(如保存固定链接设置)。
原文内容
Adds a new rewrite tag (like %postname%).
Description
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
$tagstringrequired-
Name of the new rewrite tag.
$regexstringrequired-
Regular expression to substitute the tag for in rewrite rules.
$querystringoptional-
String to append to the rewritten query. Must end in
'='. Default empty.
Source
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 );
}
Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |
Skip to note 3 content
bcworkz
In the following examples, imagine a site has a custom taxonomy ‘location’ and all posts are assigned a location term like “Paris” or “Madrid”. We add a rewrite tag “%location%” to establish the
locationquery var. We also add a rewrite rule so that an URL such as example.com/goto/madrid/budget-lodging/ is properly handled.add_action('init', 'add_my_rewrites'); function add_my_rewrites() { add_rewrite_tag('%location%', '([^&]+)', 'location='); add_rewrite_rule('^goto/([^/]*)/([^/]*)/?','index.php?location=$matches[1]&name;=$matches[2]','top'); }Even though rewrite tags look just like permalink structure tags, if you try to use your rewrite tag in a permalink structure, the URLs generated by WordPress will look something like example.com/goto/%location%/budget-lodging/. The proper term does not replace the rewrite tag as you might expect. To make your tag behave like a structure tag, use the “post_link” filter to replace the tag with the proper term.
// Assign value to %location% rewrite tag add_filter('post_link', 'my_filter_post_link', 10, 2 ); function my_filter_post_link( $permalink, $post ) { // bail if %location% tag is not present in the url: if ( false === strpos( $permalink, '%location%' ) ) { return $permalink; } $terms = wp_get_post_terms( $post->ID, 'location' ); // set location, if no location is found, provide a default value. if ( 0 < count( $terms ) ) { $location = $terms[0]->slug; } else { $location = 'timbuktu'; $location = urlencode( $location ); $permalink = str_replace('%location%', $location , $permalink ); } return $permalink; }Anytime you change something related to the Rewrite API, don’t forget to flush the rewrite rules! This can be done without code by going to Permalink Settings and clicking Save Changes. You don’t actually need to make any changes on the settings screen.
Skip to note 4 content
Akira Tachibana
(From Codex)
Example
The following will register a tag called ‘film_title’:
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:
$wp_query->query_vars['film_title']Note that using $_GET on a rewritten URL will not work, even if the rewrite includes the querystring variables. You must use $wp_query.