函数文档

the_category_head()

💡 云策文档标注

概述

the_category_head() 是一个已弃用的 WordPress 函数,用于输出当前文章的第一个分类,并支持在分类前后添加可选文本。该函数在 0.71 版本中被标记为弃用,建议使用 get_the_category_by_ID() 替代。

关键要点

  • 函数已弃用:自 WordPress 0.71 版本起,the_category_head() 被标记为弃用,推荐使用 get_the_category_by_ID() 函数。
  • 功能描述:输出当前文章的第一个分类,允许通过参数在分类前后添加自定义文本。
  • 参数说明:$before(可选,默认空字符串)用于指定分类前显示的文本;$after(可选,默认空字符串)用于指定分类后显示的文本。
  • 内部逻辑:函数通过 get_the_category() 获取文章分类,取第一个分类的 ID,然后使用 get_the_category_by_ID() 输出分类名称,并添加前后文本。
  • 相关函数:涉及 get_the_category()、get_the_category_by_ID() 和 _deprecated_function() 等核心函数。

代码示例

function the_category_head( $before = '', $after = '' ) {
    global $currentcat, $previouscat;

    _deprecated_function( __FUNCTION__, '0.71', 'get_the_category_by_ID()' );

    // Grab the first cat in the list.
    $categories = get_the_category();
    $currentcat = $categories[0]->category_id;
    if ( $currentcat != $previouscat ) {
        echo $before;
        echo get_the_category_by_ID($currentcat);
        echo $after;
        $previouscat = $currentcat;
    }
}

注意事项

  • 弃用警告:由于该函数已弃用,在开发中应避免使用,转而使用 get_the_category_by_ID() 或其他现代方法处理分类输出。
  • 兼容性:如果需要在旧版本 WordPress 中维护代码,需注意此函数可能不再受支持或引发警告。

📄 原文内容

Prints a category with optional text before and after.

Description

See also

Parameters

$beforestringoptional
Text to display before the category. Default empty.
$afterstringoptional
Text to display after the category. Default empty.

Source

function the_category_head( $before = '', $after = '' ) {
	global $currentcat, $previouscat;

	_deprecated_function( __FUNCTION__, '0.71', 'get_the_category_by_ID()' );

	// Grab the first cat in the list.
	$categories = get_the_category();
	$currentcat = $categories[0]->category_id;
	if ( $currentcat != $previouscat ) {
		echo $before;
		echo get_the_category_by_ID($currentcat);
		echo $after;
		$previouscat = $currentcat;
	}
}

Changelog

Version Description
0.71 Introduced.