WordPress Version: 6.1
/**
* Creates categories for the given post.
*
* @since 2.0.0
*
* @param string[] $categories Array of category names to create.
* @param int $post_id Optional. The post ID. Default empty.
* @return int[] Array of IDs of categories assigned to the given post.
*/
function wp_create_categories($categories, $post_id = '')
{
$cat_ids = array();
foreach ($categories as $category) {
$id = category_exists($category);
if ($id) {
$cat_ids[] = $id;
} else {
$id = wp_create_category($category);
if ($id) {
$cat_ids[] = $id;
}
}
}
if ($post_id) {
wp_set_post_categories($post_id, $cat_ids);
}
return $cat_ids;
}