WordPress主题插件开发save_post hook 钩子 修改文章发表状态 图文教程

老季最近在开发一个插件,需要在保存文章的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/

链接到文章: https://ixvps.com/47721.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注