为什么重新连接到 save_post
Why Re-hooking to save_post
说,我希望每个 post 都具有草稿状态,所以我使用下面的代码。
<?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");
}
我知道 wp_update_post()
本身会触发 save_post
挂钩,因此为了避免无限循环,我们必须在使用该函数之前使用 remove_action('save_post','mytheme_save_post')
。我的问题是为什么我需要在已经完成的情况下重新挂钩回调函数。不重新挂钩是行不通的。
起初这可能令人困惑,但正如您所说,需要避免无限循环。
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
本身不会触发任何东西。通过使用 remove_action
you're actually "pulling" the action outside of the Wordpress firing sequence,这就是如果您不重新挂钩它就无法工作的原因。
粗略地说,这就像将文件放在文件夹中,如果当您尝试访问该文件时该文件不存在,那么您会收到错误消息或您的请求被忽略。除了这里,在你重新挂钩之前它甚至不知道它存在。如果你不重新挂钩它,你几乎只是在没有触发顺序的情况下自行声明一个函数。
You can have a look at the short version of the Wordpress firing sequence here.
说,我希望每个 post 都具有草稿状态,所以我使用下面的代码。
<?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");
}
我知道 wp_update_post()
本身会触发 save_post
挂钩,因此为了避免无限循环,我们必须在使用该函数之前使用 remove_action('save_post','mytheme_save_post')
。我的问题是为什么我需要在已经完成的情况下重新挂钩回调函数。不重新挂钩是行不通的。
起初这可能令人困惑,但正如您所说,需要避免无限循环。
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
本身不会触发任何东西。通过使用 remove_action
you're actually "pulling" the action outside of the Wordpress firing sequence,这就是如果您不重新挂钩它就无法工作的原因。
粗略地说,这就像将文件放在文件夹中,如果当您尝试访问该文件时该文件不存在,那么您会收到错误消息或您的请求被忽略。除了这里,在你重新挂钩之前它甚至不知道它存在。如果你不重新挂钩它,你几乎只是在没有触发顺序的情况下自行声明一个函数。
You can have a look at the short version of the Wordpress firing sequence here.