在wordpress主题中,我创建了一个名为city
以注释形式。它可以很好地显示和保存数据。但问题是,它保存的值为空。提交带有空城市字段的表单时需要显示错误。
我添加了验证功能,但不起作用。
How to make city comment fields required??
Function.php 城市注释字段的完整代码
// Add the fields to comment form
add_filter( \'comment_form_defaults\', \'change_comment_form_defaults\');
function change_comment_form_defaults( $default ) {
$commenter = wp_get_current_commenter();
$default[ \'fields\' ][ \'email\' ] .= \'<p class="comment-form-author">\' .
\'<label for="city">\'. __(\'City\') . \'</label>
<span class="required">*</span>
<input id="city" name="city" size="30" type="text" /></p>\';
return $default;
}
// validations
add_filter( \'preprocess_comment\', \'verify_comment_meta_data\' );
function verify_comment_meta_data( $commentdata ) {
if ( ! isset( $_POST[\'city\'] ) )
wp_die( __( \'Error: please fill the required field (city).\' ) );
return $commentdata;
}
// And save the comment meta
add_action( \'comment_post\', \'save_comment_meta_data\' );
function save_comment_meta_data( $comment_id ) {
add_comment_meta( $comment_id, \'city\', $_POST[ \'city\' ] );
}
// Retrieve and display comment meta
add_filter( \'get_comment_author_link\', \'attach_city_to_author\' );
function attach_city_to_author( $author ) {
$city = get_comment_meta( get_comment_ID(), \'city\', true );
if ( $city )
$author .= " ($city)";
return $author;
}
最合适的回答,由SO网友:AddWeb Solution Pvt Ltd 整理而成
请将以下代码添加到当前主题的函数中。php
function custom_validate_city() {
if( empty($_POST[ \'city\' ])) // do you url validation here (I am not a regex expert)
wp_die( __(\'Error: please enter a city\') );
}
add_action(\'pre_comment_on_post\', \'custom_validate_city\');