PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, May 15, 2022

[FIXED] Why Re-hooking to save_post

 May 15, 2022     wordpress, wordpress-hook     No comments   

Issue

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.

  • Source @ https://developer.wordpress.org/reference/hooks/save_post/

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.



Answered By - amarinediary
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing