函数文档

single_term_title()

💡 云策文档标注

概述

single_term_title() 函数用于显示或检索分类法术语归档页面的标题,适用于分类法术语模板文件。它支持前缀参数,但前缀不会自动添加空格,需手动处理。

关键要点

  • 函数用于显示或检索分类法术语归档页面的标题,如分类、标签或自定义分类法。
  • 参数 $prefix 可选,用于在标题前添加前缀,需注意前缀不会自动添加空格。
  • 参数 $display 可选,控制是直接显示标题(默认 true)还是返回标题字符串(false)。
  • 函数内部使用 get_queried_object() 获取当前查询对象,并通过 is_category()、is_tag()、is_tax() 判断术语类型。
  • 支持过滤器:single_cat_title、single_tag_title、single_term_title,用于修改标题输出。
  • 返回类型为 string 或 void,取决于 $display 参数。

代码示例

// 示例1:显示带前缀的术语标题
single_term_title('Currently browsing ');

// 示例2:检索术语标题到变量
$current_term = single_term_title('', false);

注意事项

  • 前缀参数 $prefix 不会自动添加空格,如需空格应在参数值末尾手动添加。
  • 函数仅在分类法术语归档页面有效,否则可能返回空或无效结果。
  • 使用过滤器可以自定义标题输出,例如修改术语名称。

📄 原文内容

Displays or retrieves page title for taxonomy term archive.

Description

Useful for taxonomy term template files for displaying the taxonomy term page title.
The prefix does not automatically place a space between the prefix, so if there should be a space, the parameter value will need to have it at the end.

Parameters

$prefixstringoptional
What to display before the title.
$displaybooloptional
Whether to display or retrieve title.

Default:true

Return

string|void Title when retrieving.

Source

function single_term_title( $prefix = '', $display = true ) {
	$term = get_queried_object();

	if ( ! $term ) {
		return;
	}

	if ( is_category() ) {
		/**
		 * Filters the category archive page title.
		 *
		 * @since 2.0.10
		 *
		 * @param string $term_name Category name for archive being displayed.
		 */
		$term_name = apply_filters( 'single_cat_title', $term->name );
	} elseif ( is_tag() ) {
		/**
		 * Filters the tag archive page title.
		 *
		 * @since 2.3.0
		 *
		 * @param string $term_name Tag name for archive being displayed.
		 */
		$term_name = apply_filters( 'single_tag_title', $term->name );
	} elseif ( is_tax() ) {
		/**
		 * Filters the custom taxonomy archive page title.
		 *
		 * @since 3.1.0
		 *
		 * @param string $term_name Term name for archive being displayed.
		 */
		$term_name = apply_filters( 'single_term_title', $term->name );
	} else {
		return;
	}

	if ( empty( $term_name ) ) {
		return;
	}

	if ( $display ) {
		echo $prefix . $term_name;
	} else {
		return $prefix . $term_name;
	}
}

Hooks

apply_filters( ‘single_cat_title’, string $term_name )

Filters the category archive page title.

apply_filters( ‘single_tag_title’, string $term_name )

Filters the tag archive page title.

apply_filters( ‘single_term_title’, string $term_name )

Filters the custom taxonomy archive page title.

Changelog

Version Description
3.1.0 Introduced.

User Contributed Notes