get_tag_template()
云策文档标注
概述
get_tag_template() 函数用于检索标签模板文件的路径,遵循特定的模板层级顺序。它通过动态 Hook 允许过滤模板层级和路径。
关键要点
- 函数返回标签模板文件的完整路径字符串。
- 模板层级顺序为:tag-{slug}.php、tag-{id}.php、tag.php,其中 {slug} 和 {id} 基于当前查询的标签对象。
- 支持通过 '$type_template_hierarchy' 和 '$type_template' 动态 Hook($type 为 'tag')过滤模板层级和路径。
- 内部调用 get_query_template() 函数来获取模板路径。
- 从 WordPress 4.7.0 起,当标签 slug 包含多字节字符时,解码后的 tag-{slug}.php 会被添加到模板层级顶部。
代码示例
function get_tag_template() {
$tag = get_queried_object();
$templates = array();
if ( ! empty( $tag->slug ) ) {
$slug_decoded = urldecode( $tag->slug );
if ( $slug_decoded !== $tag->slug ) {
$templates[] = "tag-{$slug_decoded}.php";
}
$templates[] = "tag-{$tag->slug}.php";
$templates[] = "tag-{$tag->term_id}.php";
}
$templates[] = 'tag.php';
return get_query_template( 'tag', $templates );
}注意事项
- 函数依赖于 get_queried_object() 获取当前查询的标签对象,确保在适当的上下文中调用。
- 模板文件路径基于主题目录,需确保相关模板文件存在以避免返回空路径。
- 动态 Hook 可用于自定义模板选择逻辑,增强灵活性。
原文内容
Retrieves path of tag template in current or parent template.
Description
The hierarchy for this template looks like:
- tag-{slug}.php
- tag-{id}.php
- tag.php
An example of this is:
- tag-wordpress.php
- tag-3.php
- tag.php
The template hierarchy and template path are filterable via the ‘$type_template_hierarchy’ and ‘$type_template’ dynamic hooks, where $type is ‘tag’.
See also
Source
function get_tag_template() {
$tag = get_queried_object();
$templates = array();
if ( ! empty( $tag->slug ) ) {
$slug_decoded = urldecode( $tag->slug );
if ( $slug_decoded !== $tag->slug ) {
$templates[] = "tag-{$slug_decoded}.php";
}
$templates[] = "tag-{$tag->slug}.php";
$templates[] = "tag-{$tag->term_id}.php";
}
$templates[] = 'tag.php';
return get_query_template( 'tag', $templates );
}