0

$feed_category = 'Affirmations, iVideos';
 $feed_category = explode(",",$feed_category);
 $post_id = '247998';
 $yt_cat_ids = array();
 foreach ($feed_category as $value) {
  $tag_name = $value;
        $term_details = term_exists($tag_name, 'category');
        if (is_array($term_details) && count($term_details) > 0 && !empty($term_details['term_id'])) {
            $yt_cat_id = $term_details['term_id'];
            $yt_cat_ids[] = intval($yt_cat_id);
        } else {
            $tag_id = wp_insert_term($tag_name, 'category');
            if (!is_wp_error($tag_id)) {
                $yt_cat_ids[] = intval($tag_id['term_id']);
            }
        }
 }
 wp_set_post_terms($post_id, $yt_cat_ids, 'category',true);

Remove “true” if just want to use new categories

wp_set_post_terms($post_id, $yt_cat_ids, 'category');

Jagdish Sarma Asked question August 19, 2022
Add a Comment