Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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).

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!

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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);
share|improve this answer
    
Worked perfectly, thanks!! –  Michelle Aug 22 '11 at 14:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.