You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用wp_insert_comment()函数时重复提交评论的修复咨询

修复WordPress更新页面时重复提交评论的问题

你的代码重复提交评论的核心原因是wp_insert_post钩子触发场景太多——不仅是手动更新页面,自动保存草稿、生成文章修订版,甚至某些插件操作也会触发这个钩子,导致你的函数多次执行,重复插入评论。

要解决这个问题,需要在函数里加上几个过滤条件,只在手动更新页面且不是自动保存/修订版的场景下执行评论插入:

function my_project_updated_send_email( $post_id, $post, $update ) {
    // 不是更新操作(新建页面)直接跳过
    if ( !$update ) {
        return;
    }
    // 排除自动保存的情况
    if ( wp_is_post_autosave( $post_id ) ) {
        return;
    }
    // 排除修订版的情况
    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }
    // 只针对页面类型(如果需要限制为页面的话,可根据需求调整)
    if ( get_post_type( $post_id ) !== 'page' ) {
        return;
    }

    $current_user = wp_get_current_user();
    $version = do_shortcode('[field "Version"]');
    $comment_content = "This item was updated to version {$version}";

    // 额外保险:检查是否已经存在相同内容的评论,避免重复
    $existing_comment = get_comments(array(
        'post_id' => $post_id,
        'author' => $current_user->ID,
        'search' => $comment_content,
        'number' => 1
    ));
    if ( !empty($existing_comment) ) {
        return;
    }

    $data = array(
        'comment_post_ID'      => $post_id,
        'comment_content'      => $comment_content,
        'user_id'              => $current_user->ID,
        'comment_type' => '',
        'comment_approved' => 1 // 直接审核通过,可根据需求调整
    );

    wp_insert_comment( $data );
}
add_action( 'wp_insert_post', 'my_project_updated_send_email', 10, 3 );

关键说明:

  • !$update:过滤掉新建页面的操作,只处理更新场景
  • wp_is_post_autosave:排除WordPress自动保存草稿的触发
  • wp_is_post_revision:排除生成文章修订版时的触发
  • get_post_type:如果只需要针对页面生效,加上这个判断(如果是帖子可以改成'post',或者去掉这个条件)
  • 最后加的get_comments检查:作为额外保险,即使前面的过滤没拦住,也能避免插入完全相同的评论

内容的提问来源于stack exchange,提问作者idomskt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:06:02