函数文档

get_taxonomy_template()

💡 云策文档标注

概述

get_taxonomy_template() 函数用于检索自定义分类法术语模板的路径,遵循 WordPress 的模板层级结构。它基于当前查询的分类法和术语动态生成模板文件名列表,并返回匹配的模板文件完整路径。

关键要点

  • 函数返回自定义分类法术语模板文件的完整路径,支持当前或父模板的查找。
  • 模板层级结构包括:taxonomy-{taxonomy_slug}-{term_slug}.php、taxonomy-{taxonomy_slug}-{term_id}.php、taxonomy-{taxonomy_slug}.php 和 taxonomy.php,按优先级顺序匹配。
  • 可通过动态 Hook(如 'taxonomy_template_hierarchy' 和 'taxonomy_template')过滤模板层级和路径。
  • 内部使用 get_query_template() 函数来检索模板,并依赖于 get_queried_object() 获取当前查询对象。
  • 自 WordPress 6.9.0 起,添加了 taxonomy-{taxonomy_slug}-{term_id}.php 到层级中;4.7.0 版本为多字节字符术语 slug 添加了解码形式的模板。

代码示例

function get_taxonomy_template() {
    $term = get_queried_object();

    $templates = array();

    if ( ! empty( $term->slug ) ) {
        $taxonomy = $term->taxonomy;

        $slug_decoded = urldecode( $term->slug );
        if ( $slug_decoded !== $term->slug ) {
            $templates[] = "taxonomy-$taxonomy-{$slug_decoded}.php";
        }

        $templates[] = "taxonomy-$taxonomy-{$term->slug}.php";
        $templates[] = "taxonomy-$taxonomy-{$term->term_id}.php";
        $templates[] = "taxonomy-$taxonomy.php";
    }
    $templates[] = 'taxonomy.php';

    return get_query_template( 'taxonomy', $templates );
}

📄 原文内容

Retrieves path of custom taxonomy term template in current or parent template.

Description

The hierarchy for this template looks like:

  1. taxonomy-{taxonomy_slug}-{term_slug}.php
  2. taxonomy-{taxonomy_slug}-{term_id}.php
  3. taxonomy-{taxonomy_slug}.php
  4. taxonomy.php

An example of this is:

  1. taxonomy-location-texas.php
  2. taxonomy-location-67.php
  3. taxonomy-location.php
  4. taxonomy.php

The template hierarchy and template path are filterable via the ‘$type_template_hierarchy’ and ‘$type_template’ dynamic hooks, where $type is ‘taxonomy’.

See also

Return

string Full path to custom taxonomy term template file.

Source

function get_taxonomy_template() {
	$term = get_queried_object();

	$templates = array();

	if ( ! empty( $term->slug ) ) {
		$taxonomy = $term->taxonomy;

		$slug_decoded = urldecode( $term->slug );
		if ( $slug_decoded !== $term->slug ) {
			$templates[] = "taxonomy-$taxonomy-{$slug_decoded}.php";
		}

		$templates[] = "taxonomy-$taxonomy-{$term->slug}.php";
		$templates[] = "taxonomy-$taxonomy-{$term->term_id}.php";
		$templates[] = "taxonomy-$taxonomy.php";
	}
	$templates[] = 'taxonomy.php';

	return get_query_template( 'taxonomy', $templates );
}

Changelog

Version Description
6.9.0 Added taxonomy-{taxonomy_slug}-{term_id}.php to the hierarchy.
4.7.0 The decoded form of taxonomy-{taxonomy_slug}-{term_slug}.php was added to the top of the template hierarchy when the term slug contains multibyte characters.
2.5.0 Introduced.