如何在结帐 Woocommerce 中添加具有隐藏类型和默认值的自定义字段?
请检查下面我的代码:
function pord_checkout_fields( $fields ) {
$fields['billing']['quickbook'] = array(
'type' => 'hidden',
'label' => __('Purchase Order Number', 'woocommerce'),
'placeholder' => _x('Purchase Order Number', 'placeholder', 'woocommerce'),
'required' => false,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
add_filter('woocommerce_checkout_fields','pord_checkout_fields');
隐藏类型不存在,为 woocommerce 表单字段购买默认值...但您可以创建它。
这是代码:
// Create hidden checkout field type
add_filter( 'woocommerce_form_field_hidden', 'create_checkout_hidden_field_type', 5, 4 );
function create_checkout_hidden_field_type( $field, $key, $args, $value ){
return '<input type="hidden" name="'.esc_attr($key).'" id="'.esc_attr($args['id']).'" value="'.esc_attr($args['default']).'" />';
}
// Add custom hidden billing checkout field
add_filter( 'woocommerce_checkout_fields', 'custom_billing_fields' );
function custom_billing_fields( $fields ){
## HERE set the value (for this hidden checkout field)
$value = "The value";
$fields['billing']['billing_quickbook'] = array(
'type' => 'hidden',
'label' => __('Purchase Order Number', 'woocommerce'),
'placeholder' => _x('Purchase Order Number', 'placeholder', 'woocommerce'),
'required' => false,
'class' => array('form-row-wide'),
'clear' => true,
'default' => $value, // The custom field value
);
return $fields;
}
// Display the field value on the admin order edit page (after billing address)
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_custom_field_in_admin_order_meta', 10, 1 );
function display_custom_field_in_admin_order_meta($order){
echo '<p><strong>'.__('Quickbook').':</strong> ' . get_post_meta( $order->get_id(), '_billing_quickbook', true ) . '</p>';
}
代码位于活动子主题(或主题)的 function.php 文件中,或者也位于任何插件文件中。
使用(检索值):
要从
对象WC_Order
获取字段值,您将使用(与HPOS兼容):$order
$value = $order->get_meta('_billing_quickbook');
此代码经过测试并可在 WooCommerce 3+ 中运行。不适用于新的结帐块。
官方开发人员文档:使用操作和过滤器自定义结账字段
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['order']['order_comments']['placeholder'] = 'My new placeholder';
$fields['order']['order_comments']['label'] = 'My new label';
return $fields;
}