老季最近在开发一个插件,需要在保存文章的hook钩子中修改文章的状态,这里记录一下具体的方法。
这里要先移除保存文章的钩子然后再更新文章状态(不然会造成服务器500错误),然后再把钩子重新启用。官方说明文档如下:
Avoiding 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.
// this function makes all posts in the default category private
function set_private_categories($post_id) {
// If this is a revision, get real post ID
if ( $parent_id = wp_is_post_revision( $post_id ) )
$post_id = $parent_id;
// Get default category ID from options
$defaultcat = get_option( 'default_category' );
// Check if this post is in default category
if ( in_category( $defaultcat, $post_id ) ) {
// unhook this function so it doesn't loop infinitely
remove_action( 'save_post', 'set_private_categories' );
// update the post, which calls save_post again
wp_update_post( array( 'ID' => $post_id, 'post_status' => 'draft' ) );
// re-hook this function
add_action( 'save_post', 'set_private_categories' );
}
}
add_action( 'save_post', 'set_private_categories' );
WordPress官方手册:https://developer.wordpress.org/reference/hooks/save_post/