php - 在发表评论之前,如何使 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 或名称后面添加“必需”。
谢谢你的帮助!
解决方案
在设置评论数据之前有一个过滤器挂钩。它是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()">' . __( '« Back' ) . '</a></p>');
}
}
return $commentdata;
}
add_filter( 'preprocess_comment', 'wpso_verify_policy_check' );
编辑:添加了有条件的帖子类型,以便此检查仅适用于post
帖子类型。
推荐阅读
- python - 如何用单个元素替换 2d numpy 数组中重复的连续元素
- python - 内联中的语法错误 if ... else Python 中的语法
- sql-server - 特定场景下无法在select语句中进行算术运算
- sql-server - 太长。最大长度为 128。使用双引号时
- go - filepath.Join 删除点
- python - 如何在 python 下使用请求发出文件请求?
- c# - NuGet AzureServiceBus 问题
- python - 如果该行中的元素不满足某些条件,如何从二维数组中删除特定行?
- rust - 是否可以使用 BoxFnOnce 来表达一个具有更高生命周期的可变引用的闭包?
- express - 无法连接到 DigitalOcean 中的安全 websocket