我正在尝试在产品评论中添加“电话”字段(WooCommerce 3+)。 *对于未注册的用户(访客)。电话号码只能由管理员在管理面板中查看。
*电话领域需要“必填”。
我试试这段代码,但这不起作用:
function true_phone_number_field( $fields ) {
$fields['phone'] = '<p class="comment-form-phone"><label for="phone">Phone</label> <input id="phone" name="phone" type="text" value="" size="30" /></p>';
}
add_filter( 'comment_form_default_fields', 'true_phone_number_field');
// Add phone number field
function add_review_phone_field_on_comment_form() {
echo '<p class="comment-form-phone uk-margin-top"><label for="phone">' . __( 'Phone', 'text-domain' ) . '</label><span class="required">*</span><input class="uk-input uk-width-large uk-display-block" type="text" name="phone" id="phone"/></p>';
}
add_action( 'comment_form_logged_in_after', 'add_review_phone_field_on_comment_form' );
add_action( 'comment_form_after_fields', 'add_review_phone_field_on_comment_form' );
// Save phone number
add_action( 'comment_post', 'save_comment_review_phone_field' );
function save_comment_review_phone_field( $comment_id ){
if( isset( $_POST['phone'] ) )
update_comment_meta( $comment_id, 'phone', esc_attr( $_POST['phone'] ) );
}
function print_review_phone( $id ) {
$val = get_comment_meta( $id, "phone", true );
$title = $val ? '<strong class="review-phone">' . $val . '</strong>' : '';
return $title;
}
// Print phone number - remove if not needed to show in front end
/*
add_action('woocommerce_review_before_comment_meta', 'get_comment_phone' );
function get_comment_phone($comment){
echo print_review_phone($comment->comment_ID);
}
*/
//在管理列表表中列出
add_filter('manage_edit-comments_columns', 'my_add_comments_columns');
function my_add_comments_columns($my_cols) {
$temp_columns = array(
'phone' => 'Phone'
);
$my_cols = array_slice($my_cols, 0, 3, true) + $temp_columns + array_slice($my_cols, 3, NULL, true);
return $my_cols;
}
add_action('manage_comments_custom_column', 'my_add_comment_columns_content', 10, 2);
function my_add_comment_columns_content($column, $comment_ID) {
global $comment;
switch ($column) :
case 'phone' : {
echo get_comment_meta($comment_ID, 'phone', true);
break;
}
endswitch;
}
使用WordPress 5.1和WooCommerce 3.5.5测试好
您的代码应该生成一个输入字段,但它可能看起来不是,因为您使用的comment_form_default_fields
filter用于默认注释字段,如果您已登录,则会隐藏这些字段。在您注销并查看产品后,应显示电话字段评论。
此外,您没有提供任何用于将输入字段的值保存到数据库的逻辑。我想this article如果你想自己实现它可能会有所帮助。
但是,正如您使用advanced-custom-fields
标记问题一样,您可能希望跳过编码并让Advanced Custom Fields plugin处理添加输入字段并将电话号码保存到数据库。要执行此操作,只需下载并激活插件,转到“自定义字段”菜单,添加新字段组,然后创建电话输入字段。确保查看位置元框并创建一个规则,仅当Comment
is equal to
Product
显示字段组时:
这会自动将您的字段组中的字段添加到产品的评论字段中。
您必须在函数末尾返回名为“fields”的变量。
function true_phone_number_field( $fields ) {
$fields['phone'] = '<p class="comment-form-phone"><label for="phone">Phone</label> <input id="phone" name="phone" type="text" value="" size="30" /></p>';
return $fields;
}
add_filter( 'comment_form_default_fields', 'true_phone_number_field');