How to detect that the save_post hook is calling the callback associated to the current edit post page only

wordpress.stackexchange https://wordpress.stackexchange.com/questions/384897

Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top