1

Is it possible to use a custom field to assign the post category?

For example:

I have Genres custom field to my custom post type Tvseries.

Then i entered: Action, Drama, Comedy

Once i save or publish it, It will be assigned with those 3 categories i entered in the input/custom field.

1
  • You can assign multiple categories to a custom post type Tvseries directly. So why do you need the custom field Genres for?
    – Fayaz
    Jun 12, 2017 at 9:02

1 Answer 1

1

You should hook into save_post and set the categories using wp_set_object_terms():

// Add an action to run on post save
add_action( 'save_post', 'set_genre_on_save' );
function set_genre_on_save( $post_id ){
    // Check the post type
    if (is_single('tvseries')) {
        // Get the custom field data
        $custom_field_data = get_post_custom( $post_id );
        // Check if there is any genres entered in the metabox
        if (isset($custom_box_data['genre'])) {
            // Save the genre data (separated by comma) into an array
            $genre_array = explode( ',', $custom_box_data['genre'] );
            //Set the array values to lower case
            foreach ($genre_array as $genre){
                $genre = strtolower($genre);
            }
            // Set the categories for these genres
            wp_set_object_terms( $post_id, $genre_array, 'category' );
        }
    }
}

You should enter the slug or the ID of your categories in the field. for example, War Movies won't work, but war-movies will work. Also there should be no white space between the values (or you have to change ',' to ' ,').

Note that this is just an example, since you didn't post any code. You might need to change some of the values such as genres to match your custom fields / post types.

1
  • Can we assign as child category to the parent using the above code. Can you please help with this.
    – Praveen
    Jun 30, 2021 at 5:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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