1

I don't have much experience with hooks in WordPress so i have found a problem who don't look too difficult, but i can't find the answer.

In my project i have a metabox who will get the content after i make a category check inside my save_post hook.

But now i can't get the category selected and i don't know how can i know that info.

I'm using get_the_category($post_id) inside my hook, but this don't return my category.

My function is this below (and i got this from other question here):

function updatePost( $post_id, $post, $update ) {

    // Stop anything from happening if revision
    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }

    // unhook this function so it doesn't loop infinitely
    remove_action( 'save_post', 'updatePost' );

    // get post type
    $post_type = get_post_type( $post_id );

    // run codes based on post status
    $post_status = get_post_status();
    if ( $post_status != 'draft' )  {
        if ( isset( $_POST['img-destacada'] ) ) {
            get_the_category($post_id);
            // here i will put some logic to set the $img value based on my category
            $img = '';
            update_post_meta($post_id, "img-destacada", $img);
        }
    }

    // re-hook this function
    add_action( 'save_post', 'updatePost', 100, 3 );
}

How can i get the category info to then set the $img value?

1 Answer 1

1

Your code calls get_the_category() but it doesn't use the value returned.

// ...
if ( isset( $_POST['img-destacada'] ) ) {
    $categories = get_the_category($post_id);
    $img = '';
    // $categories should contain either an array of WP_Term objects,
    // or an empty array.
    if ( ! empty( $categories ) ) {
        // Here I've used the slug of the first item in the array to set the $img.
        // You may have other logic you want to use.
        $img = $categories[0]->slug . '.jpg'; 
    }
    if ( ! empty( $img ) ) {
        // Checks to make sure there's an $img set.
        update_post_meta($post_id, "img-destacada", $img);
    }
}
// ...

References

1

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.