0

I am using the save_post hook to handle updates in a post that are done via the admin edit post page.

But since I have more than ten custom post types, the save_post associated to each one of them is firing when I save ANY of all the posts.

I want to add an early return to the function that will return if the save post callback does not correspond to the current editing screen.

As follows:

function save_post_type_WHATEVER1{
    if(not editing whatever1 cpt){
    return;
    }
}

function save_post_type_WHATEVER2{
    if(not editing whatever2 cpt){
    return;
    }
}

But I don't know what I could possibly check in the if(not editing whatever2 cpt){ to achieve the desired behaviour.

I see that the URL contains a ?post=x parameter. Would it be valid enough if I just do:

function save_post_type_WHATEVER2{
    if(get_post_type($_GET['post'])!='whatever2'){
    return;
    }
}

Or will that turn into another kind of problem?

Thank you.

1 Answer 1

2

Any function hooked to the save_post hook will run whenever you save a post. That is expected behaviour.

You should use the hook save_post_{$post->post_type} to specify to which post type that callback is asociated. That way, it will only be called when saving a post of type {$post->post_type}

See the hook documentation

1
  • Wow, I never imagined this would already be a WP inbuild consideration. Amazing, thanks a lot for the information. Mar 11, 2021 at 11:03

Your Answer

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

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