1

I'm using the code below to auto-assign a CPT of 'item' to a category 'magazine', when the post is saved/updated.

function assign_item_category_automatically($post_ID) {

    global $wpdb;

    if(!wp_is_post_revision($post_ID)) {
        wp_set_object_terms( $post_ID, 'magazine', 'category');
    }
}

add_action('publish_item', 'assign_item_category_automatically');

It works fine, but the category to which it assigns is a normal category... whereas I want to assign it to a category in a custom taxonomy solely for the 'item' CPT - I don't want normal categories available to CPT posts, or custom taxonomies available to normal posts.

I have no idea how to modify this to do what I want.

  • there is not "normal" and "abnormal" categories. there is just a taxonomy named "category" and other taxonomies. then if you want another taxonomy, change the name "category" in wp_set_object_terms(... – mmm Aug 9 '16 at 9:34
  • I did a quick search and found wordpress.org/support/topic/… – bagpipper Aug 9 '16 at 9:55
  • @bagpiper... Thanks. I'd seen that page but not understood enough until I read the answer from mmm and Krzysztof. – gulliver Aug 9 '16 at 13:40
1

As Documentation says, wp_set_object_terms accepts 4 arguments: $object_id, $terms, $taxonomy, $append

  • object_id - ID of post, page, attachment or anything which is in post table
  • terms - slug(s) or id(s) or term(s)
  • taxonomy - slug of taxonomy - in your case it will be you custom taxonomy slug
  • append - whether delete all existing terms assigned to object or append new on end

Usage: wp_set_object_terms($post_id, 'magazine', 'your_taxonomy_slug', true);

  • Thanks. I now understand this better. By not understanding what I was cut/pasting, I'd used 'category' instead of the taxonomy name. – gulliver Aug 9 '16 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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