wp_create_category()
Add a new category to the database if it does not already exist.
Uses: wp_insert_category()
No Hooks.
Return
Int|WP_Error
.
Usage
wp_create_category( $cat_name, $category_parent );
- $cat_name(int|string) (required)
- Category name.
- $category_parent(int)
- ID of parent category.
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 6.1.1
function wp_create_category( $cat_name, $category_parent = 0 ) { $id = category_exists( $cat_name, $category_parent ); if ( $id ) { return $id; } return wp_insert_category( array( 'cat_name' => $cat_name, 'category_parent' => $category_parent, ) ); }