我正在努力处理一个自定义 woocommerce 结账表单的多选字段。
我通过函数创建了自定义多重选择字段:
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
$fields['billing']['_myfield'] = array(
'type' => 'select',
'id' => '_myfield',
'label' => __('My Field', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true,
'options' => [
'key1' => __('First Item', 'woocommerce'),
'key2' => __('Second Item', 'woocommerce'),
'key3' => __('Third Item', 'woocommerce'),
'key4' => __('Fourth Item', 'woocommerce')
]
);
return $fields;
}
请注意,woocommerce 函数 custom_override_checkout_fields
无法创建自定义多选字段,因此这里我们有简单的选择字段。
我决定使用jQuery来添加多个缺失的属性:
$('#_myfield').attr('multiple', 'multiple');
现在我有了多选字段,如下所示:
<select name="_myfield" id="_myfield" class="select " data-placeholder="" multiple="multiple">...</select>
问题是,订单元值无法正确更新,如果用户选择多个选项,它每次都只显示一个值,而不是一组值。
我使用此函数来更新订单的元值:
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta($order_id) {
update_post_meta($order_id, '_myfield', $_POST['_myfield'] );
}
有什么帮助吗?
也许有更好的解决方案可以在结帐的结算部分创建多选字段?
最佳答案
以下是创建自定义多选结账字段并获取订单元数据中所选值的正确方法。
所有 jQuery 代码都包含在该函数中,因此您必须删除自己的代码。
我添加了一个隐藏的输入字段,我在其中使用 jQuery 获取选定的值。下订单后,我保存此隐藏输入字段中的数据。
代码:
add_filter( 'woocommerce_checkout_fields' , 'custom_checkout_fields', 30, 1 );
function custom_checkout_fields ( $fields ) {
$domain = 'woocommerce';
$fields['billing']['multi_my_field'] = array(
'label' => __('My Field', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true,
'autocomplete' => false,
'type' => 'select',
'options' => array(
'key1' => __('First Item', $domain),
'key2' => __('Second Item', $domain),
'key3' => __('Third Item', $domain),
'key4' => __('Fourth Item', $domain),
),
);
?>
<input type="hidden" name="billing_my_field" id="billing_my_field" value="0">
<script type='text/javascript'>
jQuery(function($){
var a = 'select[name="multi_my_field"]',
b = 'input[name="billing_my_field"]';
$(a).attr('multiple', 'multiple');
$(a).change( function(){
$(b).val($(this).val());
})
});
</script>
<?php
return $fields;
}
add_action( 'woocommerce_checkout_update_order_meta', 'hidden_checkout_field_update_order_meta', 30, 1 );
function hidden_checkout_field_update_order_meta ( $order_id ) {
if( isset( $_POST['billing_my_field'] ) )
update_post_meta($order_id, '_billing_my_field', esc_attr( $_POST['billing_my_field'] ) );
}
代码位于事件子主题(或主题)的 function.php 文件中。
经过测试并有效
关于php - 在 Woocommerce 中添加自定义结账多选字段并更新订单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48971562/