get_category_parents()
云策文档标注
概述
get_category_parents() 函数用于检索指定分类的父级分类列表,并可选择性地以链接形式格式化输出。该函数内部调用 get_term_parents_list() 实现核心功能,并包含参数处理逻辑。
关键要点
- 函数参数包括:$category_id(必需,分类ID)、$link(可选,是否格式化为链接,默认false)、$separator(可选,分隔符,默认'/')、$nicename(可选,是否使用slug显示,默认false)、$deprecated(可选,已弃用参数,默认空数组)。
- 返回值:成功时返回父级分类字符串,失败时返回 WP_Error 对象。
- 自版本4.8.0起,$visited 参数已弃用并重命名为 $deprecated。
- 注意 $nicename 参数实际控制使用 term slug(true)或可读名称(false)进行显示,这可能与直觉相反。
代码示例
// 基本示例:返回当前分类的父级分类,以链接和'»'分隔符格式
// 输出示例:Internet » Blogging » WordPress »
原文内容
Retrieves category parents with separator.
Parameters
$category_idintrequired-
Category ID.
$linkbooloptional-
Whether to format with link.
Default:
false $separatorstringoptional-
How to separate categories. Default
'/'. $nicenamebooloptional-
Whether to use nice name for display.
Default:
false $deprecatedarrayoptional-
Not used.
Default:
array()
Source
function get_category_parents( $category_id, $link = false, $separator = '/', $nicename = false, $deprecated = array() ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '4.8.0' );
}
$format = $nicename ? 'slug' : 'name';
$args = array(
'separator' => $separator,
'link' => $link,
'format' => $format,
);
return get_term_parents_list( $category_id, 'category', $args );
}
Skip to note 3 content
Bence Szalai
Note that
$nicenamereally means theslug. So if the$nicenameparameter is set totrue, the function will use the termslugfor display, and using the default value offalsewill use the human readable display name of the term.May be confusing at first, as some of us may think human readable names are nicer than slugs.
Skip to note 4 content
Codex
Basic Example
Returns the parent categories of the current category with links separated by ‘»’
will output: