php – Custom field to category-ThrowExceptions

Exception or error:

I use to see this script to auto fields to a category

function wpse_248054(){

    $custom_field_name = 'Genre';

    $posts = new WP_Query(
            'posts_per_page' => -1,
            'post_type'=> 'post',

    foreach($posts->posts as $post){

        $meta = get_post_meta($post->ID, 'Genre', true);

        if(! empty( $meta )){
            $term_id = wp_create_category($meta, 3); // 2nd argument, parent id (optional)

            $new_post_cat = wp_set_post_terms( $post->ID, $term_id, 'category', true );


add_action('admin_init', 'wpse_248054');

The meta key is Genre.

But contains comma separator (example: Short, Western, Drama)

And this script creates a category Short, Western, Drama altogether, who can I adjust this?

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *