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

如何基于WordPress评论自定义字段实现差异化自动回复及条件拦截?

解决方案

你需要调整代码逻辑,先获取用户提交的likebook字段值,再根据值设置对应回复内容,同时修复原代码的语法错误。以下是修改后的完整代码:

add_action( 'comment_post', 'author_new_comment', 10, 3 );
function author_new_comment( $comment_ID, $comment_approved, $commentdata ){
    $comment_parent = (int) $commentdata['comment_parent'];
    
    // 如果新评论是对其他评论的回复,则不执行任何操作
    if ( $comment_parent !== 0 ) {
        return;
    } 

    // 获取用户提交的likebook字段值并过滤
    $like_book = isset( $_POST['likebook'] ) ? sanitize_text_field( $_POST['likebook'] ) : '';

    // 验证是否为预期的有效值,无效则终止
    if ( empty( $like_book ) || !in_array( $like_book, ['yes', 'no'] ) ) {
        return;
    }

    // 将自定义字段值保存到评论元数据,方便后续查看或调用
    add_comment_meta( $comment_ID, 'likebook', $like_book, true );

    // 根据字段值设置对应回复内容
    switch ( $like_book ) {
        case 'yes':
            $reply_content = '感谢您的认可,客户满意始终是我们的目标。';
            break;
        case 'no':
            $reply_content = '我们会努力做得更好。';
            break;
        default:
            $reply_content = '';
    }

    // 无有效回复内容则不执行操作
    if ( empty( $reply_content ) ) {
        return;
    }

    $commentdata = [
        'comment_post_ID'      => $commentdata['comment_post_ID'],
        'comment_author'       => 'admin',
        'comment_author_email' => 'admin@example.com',
        'comment_author_url'   => 'http://example.com',
        'comment_content'      => $reply_content,
        'comment_type'         => 'comment',
        'comment_parent'       => $comment_ID,
        'user_ID'              => 1,
        'comment_approved'     => 1, // 自动批准管理员回复,无需审核
    ];
  
    wp_new_comment( $commentdata );
}

关键修改说明:

  • 修复语法错误:修正原代码中缺失闭合括号的问题,同时调整字段判断逻辑,确保只处理有效值。
  • 安全处理字段值:用sanitize_text_field过滤用户输入,避免恶意内容,同时验证值是否为预期的yes或no。
  • 保存元数据:通过add_comment_meta将用户选择的likebook值存入评论元数据,便于后续管理或二次开发使用。
  • 动态匹配回复:通过switch语句根据字段值自动切换对应的中文回复内容。
  • 自动批准回复:在回复参数中加入comment_approved => 1,确保管理员的自动回复直接显示,无需额外审核。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 10:50:24