How to Assign Category to a Post Automatically

Copy and Paste the Below code in you theme functions.php.

 function auto_add_category ($post_id = 0) {
     if (!$post_id) return;
     $tag_categories = array ( //  add multiple items as shown 'Tag Name' => 'Categroy Name'
       'toys' => 'Kids',
       'apple' => 'Fruits',
     );
     $post_tags = get_the_tags($post_id);
     foreach ($post_tags as $tag) {
       if ($tag_categories[$tag->name] ) {
         $cat_id = get_cat_ID($tag_categories[$tag->name]);
         if ($cat_id) {
           $result =  wp_set_post_terms( $post_id, $tags = $cat_id, $taxonomy = 'category', $append = true );
         }
       }
     }
   }
add_action('publish_post','auto_add_category');
?>

No comments:

Post a Comment