category_exists()
云策文档标注
概述
category_exists() 函数用于检查 WordPress 中是否存在指定名称的分类,并可选择性地指定父分类 ID。它基于 term_exists() 实现,返回分类 ID 或 null。
关键要点
- 函数检查分类是否存在,参数包括分类名称(必需)和父分类 ID(可选)。
- 返回值为字符串形式的分类 ID 或 null,表示是否存在。
- 该函数仅在 wp-admin 中可用,前端使用会报错,建议使用 term_exists() 替代。
- 相关函数包括 term_exists()、wp_create_category() 和 wp_create_categories()。
代码示例
function category_exists( $cat_name, $category_parent = null ) {
$id = term_exists( $cat_name, 'category', $category_parent );
if ( is_array( $id ) ) {
$id = $id['term_id'];
}
return $id;
}注意事项
此函数仅在后端(wp-admin)可用,前端使用会导致错误,应改用 term_exists()。
原文内容
Checks whether a category exists.
Description
See also
Parameters
$cat_nameint|stringrequired-
Category name.
$category_parentintoptional-
ID of parent category.
Default:
null
Source
function category_exists( $cat_name, $category_parent = null ) {
$id = term_exists( $cat_name, 'category', $category_parent );
if ( is_array( $id ) ) {
$id = $id['term_id'];
}
return $id;
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 2 content
keesiemeijer
Beware this function is only available in the wp-admin and will throw an error if used in the front end of your site. Use term_exists instead.