wp_create_category()WP 2.0.0

Add a new category to the database if it does not already exist.

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

0

#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 );
0

#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() code WP 6.5.3

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,
		)
	);
}