Php WordPress.org,单击按钮,更改发布->;注释“U状态=”;开放式;至;“已关闭”;从前端

Php WordPress.org,单击按钮,更改发布->;注释“U状态=”;开放式;至;“已关闭”;从前端,php,wordpress,Php,Wordpress,我正试图通过点击WordPress.org网站上的一个按钮,了解如何将一篇帖子的评论状态从“打开”改为“关闭”。我知道我可以在后端做这件事(作为管理员),但我需要它在前端工作(对于特定的用户角色)。我尝试将“wp_update_post($my_args)”与“add_action('save_post'、'my_function')”结合使用,但到目前为止运气不佳。谢谢你的帮助。 我试图使用的功能,来自WordPress Codex,就在这里 function my_function( ){

我正试图通过点击WordPress.org网站上的一个按钮,了解如何将一篇帖子的评论状态从“打开”改为“关闭”。我知道我可以在后端做这件事(作为管理员),但我需要它在前端工作(对于特定的用户角色)。我尝试将“wp_update_post($my_args)”与“add_action('save_post'、'my_function')”结合使用,但到目前为止运气不佳。谢谢你的帮助。 我试图使用的功能,来自WordPress Codex,就在这里

function my_function( ){

    if ( ! wp_is_post_revision( 251 ) ){

        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'my_function');

        // update the post, which calls save_post again
        $my_args = array(
            'ID'           => 251,
            'comment_status'   => 'closed'
        );
        wp_update_post( $my_args );

        // re-hook this function
        add_action('save_post', 'my_function');
    }
}
add_action('save_post', 'my_function');

我对WordPress Codex进行了深入研究,发现了这段代码(代码正在根据我的需要进行一些修改)

//Change post comment status from "open" to "closed"
global $wpdb;

if ( ! $post = get_post( 251 ) ) return;

if ( 'closed' == $post->comment_status ) return;
    
$wpdb->update( $wpdb->posts, array( 'comment_status' => 'closed' ), array( 'ID' => $post->ID ) );

clean_post_cache( $post->ID );
    
$old_status = $post->comment_status;

$post->comment_status = 'closed';

wp_transition_post_status( 'closed', $old_status, $post );