0

i am trying to assign multiple categories to my Custom Post Type using advanced custom field named 'cat'. But there is nothing saving to my categories. Any help?

<?php
// 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('hvm')) {
        // Get the custom field data
        $custom_field_data = get_post_custom( $post_id );
        // Check if there is any category entered in the metabox
        if (isset($custom_box_data['cat'])) {
            // Save the data (separated by comma) into an array
            $genre_array = explode( ',', $custom_box_data['cat'] );
            //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' );
        }
    }
}
?>

1 Answer 1

0

You can not use is_single() conditional tag here.

You can check the type of post in the function this way:

add_action( 'save_post', 'set_genre_on_save', 20, 3 );
function set_genre_on_save( $post_id, $post, $update ) {
    if ($post->post_type != 'hvm')
        return;

    // ...
}  

You can also attach the function to the action hook save_post_{post_type}, which is triggered only for the {post_type} type. Then there is no need to check the type of post inside the function.

add_action( 'save_post_hvm', 'set_genre_on_save', 20, 3 );
12
  • Still does nothing, any idea how it comes?
    – Dennis
    Commented May 28, 2019 at 12:01
  • @Dennis Are you sure that $custom_box_data['cat'] is a string, not an array? It seems to me that get_post_custom() returns every meta field as an array.
    – nmr
    Commented May 28, 2019 at 12:16
  • what should i use instead, im kinda stuck on this..
    – Dennis
    Commented May 28, 2019 at 12:43
  • @Dennis If you have one cat custom field per post, try using get_post_meta custom_field_data = get_post_meta( $post_id, 'cat', true);.
    – nmr
    Commented May 28, 2019 at 13:02
  • I have multiple fields, one field is 'cat' per cpt. The above solution still dont write the categories.
    – Dennis
    Commented May 28, 2019 at 13:08

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.