wp_create_category( int|string $cat_name, int $category_parent ): int|WP_Error
Adds a new category to the database if it does not already exist.
Contents
Parameters
-
$cat_name
int|string Required -
Category name.
-
$category_parent
int Optional -
ID of parent category.
Return
int|WP_Error
More Information
Parameters:
$cat_name
: Name for the new category.$parent
: Category ID of the parent category.
Returns:
- 0 on failure, category id on success.
wp_create_category() is a thin wrapper around wp_insert_category() .
Because this is a wrapper, it is not suitable for entering a complex custom taxonomy element.
If the category already exists, it is not duplicated. The ID of the original existing category is returned without error.
Source
File: wp-admin/includes/taxonomy.php
.
View all references
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,
)
);
}
Changelog
Version | Description |
---|---|
2.0.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Examples
In order to create a simple category use:
To create a category that is a child of Uncategorized (or whatever category has the ID 0), use:
To get id of category created and put value in variable:
An example of how you can use the wp_create_category() function.
In this example:
$category_name
is set to “New Category”, which is the name of the category you want to create.$parent_category_id
is set to 3, which is the ID of the parent category where you want to create the new category. You should replace this with the actual ID of the desired parent category.The
wp_create_category()
function is called with both the category name and the parent category ID as arguments. If the category is successfully created, it will return the category ID as an integer. If there’s an error during the creation process, it will return aWP_Error
object.The code then checks if the result is a
WP_Error
object usingis_wp_error()
. If it’s not an error, it means the category was created successfully, and it will display a message with the category ID. If an error occurred, it will display an error message using theget_error_message()
method of theWP_Error
object.