如何在发表评论之前选中 Wordpress 评论复选框 mandatory/required?

How can I make the Wordpress comment checkbox mandatory/required before posting a comment?

我禁用了 Wordpress 功能 'Show comments cookies opt-in checkbox, allowing comment author cookies to be set.' 但我在评论表单中手动添加了一个复选框,因为我想更改复选框的标签。

我通过将以下代码添加到我的子主题的 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;

}

这工作正常,但现在我想让这个复选框成为强制性的,这样用户必须在按下 'Post comment' 按钮之前检查它。

因此,如果未选中该复选框,用户在单击 'Post comment' 按钮时应该会看到一条错误消息。

我该怎么做?到目前为止我发现的所有建议都不起作用,例如在输入 ID 或名称后面添加 'required'。

感谢您的帮助!

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

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 类型条件,以便此检查仅适用于 post post 类型。