wp_create_category()
Simplified function for adding a category, which requires the name of the new category and, if needed, the ID of the parent category.
Before adding the category, the function checks if there is already a category with the specified parameters.
Uses: wp_insert_category()
No Hooks.
Returns
Int. 0 - on failure. ID of the added category if the category was successfully added.
Usage
wp_create_category( $cat_name, $parent );
- $cat_name(string) (required)
- Name of the new category.
- $parent(int)
- ID of the category that will be the parent for the added one.
Examples
#1 Create a category
In order to create a simple category use:
wp_create_category( 'My category name' );
To create a category that is a child of the category with ID = 6, you must specify the second parameter:
wp_create_category( 'Child of My Category', 6 );
To get id of category created and put value in variable:
$cat_id = wp_create_category( 'Child of My Category', 6 );
#2 Check if a category was created
$cat_id = wp_create_category( 'Miscellaneous' );
if( $cat_id ){
echo 'Created';
}
else {
echo 'Not created';
}
Changelog
| Since 2.0.0 | Introduced. |
wp_create_category() wp create category code WP 7.0
function wp_create_category( $category_name, $category_parent = 0 ) {
$id = category_exists( $category_name, $category_parent );
if ( $id ) {
return (int) $id;
}
return wp_insert_category(
array(
'cat_name' => $category_name,
'category_parent' => $category_parent,
)
);
}