wp_create_categories( string[] $categories, int $post_id =  ): int[]

In this article

Creates categories for the given post.

Parameters

$categoriesstring[]required
Array of category names to create.
$post_idintoptional
The post ID.

Default:''

Return

int[] Array of IDs of categories assigned to the given post.

Source

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

Changelog

VersionDescription
2.0.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.