Automatic category for a Custom Post Type

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