如何在发表评论之前强制/要求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!
我禁用了Wordpress功能'显示评论cookie选择复选框,允许设置评论作者cookie。' 但我手动在评论表单中添加了一个复选框,因为我想更改复选框的标签。 p>
我这样做是通过将以下代码添加到我的子主题的functions.php中: p>
add_filter('comment_form_default_fields','tu_comment_form_change_cookies_consent');
函数tu_comment_form_change_cookies_consent($ fields){
$ commenter = wp_get_current_commenter();
$ consent = empty ($ commenter ['comment_author_email'])? '':'checked =“checked”';
$ fields ['cookies'] ='&lt; p class =“comment-form-cookies-consent”&gt;&lt; input id =“wp-comment- cookies-consent“name =”wp-comment-cookies-consent“type =”checkbox“value =”yes“'。 $同意。 '/&gt;' 。
'&lt; label for =“wp-comment-cookies-consent”&gt;使用此评论表单即表示您同意我们的隐私政策&lt; / label&gt;&lt; / p&gt;';
返回$ fields;
}
code> pre>
这个工作正常,但现在我想强制使用此复选框,以便用户在按“发表评论”按钮之前必须检查它。 / p>
因此,如果取消选中该复选框,则用户在单击“发表评论”按钮时应看到错误消息。 p>
我该怎么做 ? 到目前为止我找到的所有建议都没有用,例如在输入ID或名称后添加'required'。 p>
感谢您的帮助! p>
div >
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()">' . __( '« 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.