Automatic category for a Custom Post Type

I’ve created two new CPTs called ‘Movie Reviews’ and “Game Reviews”. In my website I also have one category called ‘Reviews’ where you can find two sub-categories: ‘Movie Reviews’ and ‘Game Reviews’.

I saw that I can set a specific taxonomy for each CPT, but what I want is to automaticly set one specific category to every post in this CPT. For example, if I write a movie review in my CPT ‘Movie Reviews’, I want to automaticly set the category of this post as ‘Reviews’ – ‘Movie Reviews’, because every post under this CPT will be like that.

Is this possible? How should I proceed?

1 Answer
1

You will need to run an action to check post type every time a new post is being created.

Just add this code in functions.php in your active theme folder located in “wp-content/themes

function post_auto_cat( $post_ID ) {
    $post_type="Your custom post type. For example: movie";
    $cat_id = 123; // Your reviews category id (for example: 123)
    $post_categories=array($cat_id);

    // check if current post type is movie review
    if(get_post_type($post_ID)==$post_type) {
        // assign a category for this post by default
        wp_set_post_categories( $post_ID, $post_categories );
    }

   return $post_ID;
}
add_action( 'publish_post', 'post_auto_cat' );

It will assign the category for each post with the custom post type ‘movie’ to the category reviews with the ID 123 – EVERY time a new post gets published.

If you wanted to make this check fires every time a post is being updated (not just published) you will have to change the last line from

add_action( 'publish_post', 'post_auto_cat' );

to

add_action( 'save_post', 'post_auto_cat' );

Remember to change the values in the above mentioned code to your values (post type & category id)

This code looks legit but i didn’t test so remember to backup your files/database before using it.

Leave a Comment