您的选择字段中缺少一些内容,最好使用挂钩函数将其嵌入到“添加到购物车”表单中的产品中(如果您希望能够获取过账价值)。
下面是显示和保存所选大小的完整方法,包括字段验证
1) 显示“添加到购物车”按钮之前的“选择”字段:
// Display Select field before add to cart button
add_action( \'woocommerce_before_add_to_cart_button\', \'sizes_before_add_to_cart_button\', 0 );
function sizes_before_add_to_cart_button() {
global $product;
// Only on simple products
if( ! $product->is_type(\'simple\') ) return;
// When product sizes are available
if ( $sizes = $product->get_attribute( \'size\' ) ) :
$sizes = explode(", ",$sizes);
$required = \' <abbr class="required" title="required">*</abbr></label>\';
echo \'<p class="form-row form-row-wide" id="product-size-field">
<label for="product-size">\' . __(\'Sizes:\') . $required . \'</label>
<select class="product-size" name="product-size" id="product-size">
<option value="">\' . __("Choose your size") . \'</option>\';
foreach( $sizes as $size ){
echo \'<option value="\' . $size . \'">\' . $size . \'</option>\';
}
echo \'</select>
</p><br>\';
endif;
}
2) 现场验证:
add_filter( \'woocommerce_add_to_cart_validation\', \'filter_add_to_cart_validation\', 10, 4 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = 0 ) {
$product = wc_get_product($product_id);
// Only on simple products and When product sizes are available
if( ! $product->is_type(\'simple\') && ! $product->get_attribute( \'size\' ) )
return $passed;
if( isset( $_POST[\'product-size\'] ) && empty( $_POST[\'product-size\'] ) ) {
wc_add_notice( __("Please choose your size.", "woocommerce" ), \'error\' );
$passed = false;
}
return $passed;
}
3) 将所选大小添加为自定义购物车项目数据:
add_filter( \'woocommerce_add_cart_item_data\', \'add_size_to_cart_item_data\', 10, 3 );
function add_size_to_cart_item_data($cart_item_data, $product_id, $variation_id ){
if( isset( $_POST[\'product-size\'] ) ) {
$cart_item_data[\'product-size\'] = esc_attr( $_POST[\'product-size\'] );
}
return $cart_item_data;
}
4)在购物车和结账页面中的产品名称下显示选定的尺寸
add_filter( \'woocommerce_get_item_data\', \'display_size_on_cart_item\', 10, 2 );
function display_size_on_cart_item( $cart_item_data, $cart_item ) {
if ( isset( $cart_item[\'product-size\'] ) ){
$cart_item_data[] = array(
\'name\' => __(\'Size\'),
\'value\' => $cart_item[\'product-size\'],
);
}
return $cart_item_data;
}
5) 将所选大小另存为订单项元数据,并将其显示在所有位置
add_action(\'woocommerce_checkout_create_order_line_item\', \'save_order_item_product_fitting_color\', 10, 4 );
function save_order_item_product_fitting_color( $item, $cart_item_key, $cart_item, $order ) {
if( isset($cart_item[\'product-size\']) ) {
$item->update_meta_data( \'Size\', $cart_item[\'product-size\'] );
}
}
代码进入功能。活动子主题(或活动主题)的php文件。已测试并正常工作。