Add category to custom post type automatically, using category slug

I’m using this excellent function to automatically add a category to my custom post type “Videos” on publish, if there’s no category already chosen. This works great:

function add_video_category_automatically($post_ID) {
    global $wpdb;
    if(!has_term('','category',$post_ID)){
        $cat = array(394);
        wp_set_object_terms($post_ID, $cat, 'category');
    }
}
add_action('publish_videos', 'add_video_category_automatically');

But, I’d really like to get the category ID via the slug, so that I don’t have to change it manually when I’m testing on localhost vs the live site (which may have a different ID for that category as localhost and the live site aren’t in sync).

Read More

I’ve tried a number of options but all of them result in a category of “394” being assigned to new posts, rather than “Videos”. Here’s my latest attempt. Can you tell me where I’m going wrong?

function add_video_category_automatically($post_ID) {
    global $wpdb;
    if(!has_term('','category',$post_ID)){
        $category = get_term_by( 'slug', 'videos', 'category' );
        $cat = array($category->term_id);
        wp_set_object_terms($post_ID, $cat, 'category');
    }
}
add_action('publish_videos', 'add_video_category_automatically');

Thank you!

Related posts

Leave a Reply

1 comment

  1. wp_set_object_terms Works better with term slug instead of term id so change this line:

    $cat = array($category->term_id);
    

    to:

     $cat = array($category->slug);