duan1979768678 2019-05-04 17:20
浏览 192
已采纳

如何在发表评论之前强制/要求Wordpress评论复选框?

I disabled the Wordpress function 'Show comments cookies opt-in checkbox, allowing comment author cookies to be set.' but I added a checkbox in the comment form manually because I wanted to change the label of the checkbox.

I did this by adding the following code to the functions.php of my child theme:

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;

}

This is working fine but now I wanna have this checkbox mandatory so that the user has to check it before pressing the 'Post comment' button.

So if the checkbox is unchecked, the user should see a error message when clicking on the 'Post comment' button.

How can I do that? All the suggestions I found so far are not working, like for example adding 'required' behind the input id or name.

Thanks for your help!

  • 写回答

1条回答 默认 最新

  • douhao1956 2019-05-07 06:17
    关注

    There is a filter hook just before comment data is set. It is preprocess_comment. In that hook I have checked if the checkbox is set or not. If not it will block to post comment data.

    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' );
    

    Edit: Added post type conditional so that this check is applied to post post type only.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?