wp_update_category()
云策文档标注
概述
wp_update_category() 是 wp_insert_category() 的别名函数,用于更新现有分类的部分字段。它通过合并新旧字段并调用 wp_insert_category() 来实现更新操作。
关键要点
- 函数是 wp_insert_category() 的别名,主要用于更新分类,而非创建新分类。
- 参数 $catarr 必须包含 'cat_ID' 键以指定要更新的分类 ID,其他字段可选。
- 函数返回更新后分类的 ID(成功时)或 false(失败时)。
- 内部实现包括获取原始分类数据、合并新旧字段,并调用 wp_insert_category() 完成更新。
代码示例
function wp_update_category( $catarr ) {
$cat_id = (int) $catarr['cat_ID'];
if ( isset( $catarr['category_parent'] ) && ( $cat_id === (int) $catarr['category_parent'] ) ) {
return false;
}
// First, get all of the original fields.
$category = get_term( $cat_id, 'category', ARRAY_A );
_make_cat_compat( $category );
// Escape data pulled from DB.
$category = wp_slash( $category );
// Merge old and new fields with new fields overwriting old ones.
$catarr = array_merge( $category, $catarr );
return wp_insert_category( $catarr );
}注意事项
- 如果 $catarr 中的 'category_parent' 设置为与 'cat_ID' 相同,函数会返回 false,防止循环引用。
- 函数依赖于 wp_insert_category()、get_term()、_make_cat_compat() 和 wp_slash() 等辅助函数。
- 自 WordPress 2.0.0 版本引入,用于向后兼容和简化分类更新操作。
原文内容
Aliases wp_insert_category() with minimal args.
Description
If you want to update only some fields of an existing category, call this function with only the new values set inside $catarr.
Parameters
$catarrarrayrequired-
The
'cat_ID'value is required. All other keys are optional.
Source
function wp_update_category( $catarr ) {
$cat_id = (int) $catarr['cat_ID'];
if ( isset( $catarr['category_parent'] ) && ( $cat_id === (int) $catarr['category_parent'] ) ) {
return false;
}
// First, get all of the original fields.
$category = get_term( $cat_id, 'category', ARRAY_A );
_make_cat_compat( $category );
// Escape data pulled from DB.
$category = wp_slash( $category );
// Merge old and new fields with new fields overwriting old ones.
$catarr = array_merge( $category, $catarr );
return wp_insert_category( $catarr );
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |