get_category_template()
云策文档标注
概述
get_category_template() 函数用于检索当前或父模板中分类模板的路径。它遵循特定的模板层级结构,并可通过动态钩子进行过滤。
关键要点
- 函数返回分类模板文件的完整路径字符串。
- 模板层级顺序为:category-{slug}.php、category-{id}.php、category.php,其中 {slug} 和 {id} 基于当前查询的分类对象。
- 支持通过动态钩子 '$type_template_hierarchy' 和 '$type_template'($type 为 'category')过滤模板层级和路径。
- 内部调用 get_query_template() 函数来获取模板路径。
代码示例
function get_category_template() {
$category = get_queried_object();
$templates = array();
if ( ! empty( $category->slug ) ) {
$slug_decoded = urldecode( $category->slug );
if ( $slug_decoded !== $category->slug ) {
$templates[] = "category-{$slug_decoded}.php";
}
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
}
$templates[] = 'category.php';
return get_query_template( 'category', $templates );
}注意事项
- 从版本 4.7.0 开始,当分类 slug 包含多字节字符时,解码后的 category-{slug}.php 会被添加到模板层级的顶部。
- 函数自版本 1.5.0 引入。
原文内容
Retrieves path of category template in current or parent template.
Description
The hierarchy for this template looks like:
- category-{slug}.php
- category-{id}.php
- category.php
An example of this is:
- category-news.php
- category-2.php
- category.php
The template hierarchy and template path are filterable via the ‘$type_template_hierarchy’ and ‘$type_template’ dynamic hooks, where $type is ‘category’.
See also
Source
function get_category_template() {
$category = get_queried_object();
$templates = array();
if ( ! empty( $category->slug ) ) {
$slug_decoded = urldecode( $category->slug );
if ( $slug_decoded !== $category->slug ) {
$templates[] = "category-{$slug_decoded}.php";
}
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
}
$templates[] = 'category.php';
return get_query_template( 'category', $templates );
}