首页 > 解决方案 > 在发表评论之前,如何使 Wordpress 评论复选框成为强制性/必需的?

问题描述

我禁用了 Wordpress 功能“显示评论 cookie 选择加入复选框,允许设置评论作者 cookie”。但我手动在评论表单中添加了一个复选框,因为我想更改复选框的标签。

我通过将以下代码添加到我的子主题的 functions.php 来做到这一点:

add_filter( 'comment_form_default_fields', 'tu_comment_form_change_cookies_consent' );
function tu_comment_form_change_cookies_consent( $fields ) {
    $commenter = wp_get_current_commenter();

    $consent   = empty( $commenter['comment_author_email'] ) ? '' : ' checked="checked"';

    $fields['cookies'] = '<p class="comment-form-cookies-consent"><input id="wp-comment-cookies-consent" name="wp-comment-cookies-consent" type="checkbox" value="yes"' . $consent . ' />' .
                     '<label for="wp-comment-cookies-consent">By using this comment form you agree with our Privacy Policy</label></p>';
    return $fields;

}

这工作正常,但现在我想强制使用此复选框,以便用户在按下“发表评论”按钮之前必须检查它。

因此,如果未选中该复选框,则用户在单击“发表评论”按钮时应该会看到一条错误消息。

我怎样才能做到这一点?到目前为止我发现的所有建议都不起作用,例如在输入 ID 或名称后面添加“必需”。

谢谢你的帮助!

标签: phpwordpressfunctioncheckboxrequired

解决方案


在设置评论数据之前有一个过滤器挂钩。它是preprocess_comment。在那个钩子中,我检查了复选框是否已设置。如果不是,它将阻止发布评论数据。

function wpso_verify_policy_check( $commentdata ) {
    if ( 'post' === get_post_type( $_POST['comment_post_ID'] ) ) {
        if ( ! isset( $_POST['wp-comment-cookies-consent'] ) ) {
            wp_die( '<strong>' . __( 'WARNING: ' ) . '</strong>' . __( 'You must accept the Privacy Policy.' ) . '<p><a href="javascript:history.back()">' . __( '&laquo; Back' ) . '</a></p>');
        }
    }
    return $commentdata;
}

add_filter( 'preprocess_comment', 'wpso_verify_policy_check' );

编辑:添加了有条件的帖子类型,以便此检查仅适用于post帖子类型。


推荐阅读