automatically add category to custom post type
-
Hi,
I am trying to automatically set a category per custom post type. I already created categories CAT1, CAT2, CAT3 and custom post types CPT1, CPT2, CPT3. Now I would like to assign:
CAT1 to CPT1
CAT2 to CPT2
CAT3 to CPT3I can get this to work in my functions.php with what I have so far but only for one category and one custom post type. I tried to change this into a condition so I can assign each category to each of the custom post types, but I am missing something and I can’t get the conditions to work.
Thank you already for your help ??
function wpc_update_post_terms( $post_id ) { if ( $parent = wp_is_post_revision( $post_id ) ) $post_id = $parent; $post = get_post( $post_id ); if ( $post->post_type != 'CPT1' ) return; //adding the category $categories = wp_get_post_categories( $post_id ); $newcat1 = get_term_by( 'slug', 'CAT1', 'category' ); array_push( $categories, $newcat1->term_id ); wp_set_post_categories( $post_id, $categories ); } add_action( 'wp_insert_post', 'wpc_update_post_terms' );
- The topic ‘automatically add category to custom post type’ is closed to new replies.