如何在woocommerce结帐页面中创建具有多个选项的自定义选择框,其值已保存为数据库中的[[作为用户元数据,这样该值将自动填充到字段中,并且在放置时他不必再次选择以后的订单。
我已经尝试过此自定义代码,您可以看到in my previous question here。下订单时如何保存选择框选择的值
作为用户元数据
?“ Save custom checkout field value as user data on WooCommerce”和“ Custom checkout random select field in Woocommerce”回答线程:
// display a custom checkout select field
add_action( 'woocommerce_after_order_notes', 'display_custom_checkout_select_field', 10, 1 );
function display_custom_checkout_select_field( $checkout )
{
// Heading
echo '<h4>' . __("Custom field Heading", "woocommerce") . '</h4>'; // Optional
woocommerce_form_field( 'checkout_user_choice', array(
'type' => 'select',
'class' => array( 'select-box'),
'label' => __("Custom select box", "woocommerce"),
'options' => array(
'' => __("Chose something please…", "woocommerce"),
'value1' => __("Choice 1", "woocommerce"),
'value2' => __("Choice 2", "woocommerce"),
'value3' => __("Choice 3", "woocommerce"),
),
'required' => true, // Or false
), $checkout->get_value( 'checkout_user_choice' ) );
}
// Custom Checkout field validation
add_action('woocommerce_checkout_process', 'custom_checkout_field_validation');
function custom_checkout_field_validation() {
if ( isset($_POST['checkout_user_choice']) && empty($_POST['checkout_user_choice']) ) {
wc_add_notice( '<strong>'. __("Please select a value", "woocommerce") . '</strong>', 'error' );
}
}
// Save custom checkout field value as order meta data
add_action( 'woocommerce_checkout_create_order', 'custom_checkout_field_update_order_meta', 10, 2 );
function custom_checkout_field_update_order_meta( $order, $data ){
if ( isset($_POST['checkout_user_choice']) && ! empty($_POST['checkout_user_choice']) ) {
$order->update_meta_data( '_checkout_user_choice', esc_attr( $_POST['checkout_user_choice'] ) ); // Order meta data
}
}
// Save custom checkout field value as USER meta data
add_action('woocommerce_checkout_update_customer','custom_checkout_field_update_user_meta', 10, 2 );
function custom_checkout_field_update_user_meta( $customer, $data ){
if ( isset($_POST['checkout_user_choice']) && ! empty($_POST['checkout_user_choice']) ) {
$customer->update_meta_data( 'checkout_user_choice', esc_attr( $_POST['checkout_user_choice'] ) ); // User meta data
}
}
// display custom checkout field value in the order admin panel
add_action( 'woocommerce_admin_order_data_after_order_details', 'display_user_choice_to_admin_order', 10, 1 );
function display_user_choice_to_admin_order( $order ){
if( $value = $order->get_meta( '_checkout_user_choice' ) ) {
echo '<br style="clear:both">
<p><strong>' . __( "Custom Select choice", "woocommerce" ) . ':</strong> ' . $value . '</p>';
}
}
代码进入您的活动子主题(活动主题)的functions.php文件中。经过测试和工作。