Search code examples
wordpresswordpress-hook

Why Re-hooking to save_post


Say, I want every post to have draft status so I use the code below.

<?php
add_action('save_post', 'mytheme_save_post');
function mytheme_save_post($post_id) {
remove_action('save_post','mytheme_save_post');

wp_update_post( array("ID"=>$post_id, "post_status"=>'draft'));

 add_action("save_post","mytheme_save_post");
}

I know that wp_update_post() itself trigger save_post hook so to avoid infinite loop we have to use remove_action('save_post','mytheme_save_post') before using that function. My question is why do I need to re-hook the the callback function while I am already done. Without re-hooking it is not working.


Solution

  • This might be confusing at first but like you said it is required to avoid infinite loops.

    If you are calling a function such as wp_update_post that includes the save_post hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the function you need, then re-hook it afterward.

    add_action enables to hook a function on to a specific action, here init.

    Fires after WordPress has finished loading but before any headers are sent.

    add_action doesn't trigger anything by itself. By using remove_action you're actually "pulling" the action outside of the Wordpress firing sequence, which is why it is not working if you don't re-hook it.

    In crude terms, it's like placing a file in a folder, if the file isn't there when you try to access it then you get an error or your request gets ignored. exept here it doesn't even know it exist before you re-hook it. If you don't re-hook it you're pretty much just declaring a function by itself with no firing order.

    You can have a look at the short version of the Wordpress firing sequence here.