我有文件 custom.php,在哪里添加带有自定义数据的产品(field_wrap_name 和 field_wrap_img)WC()->cart->add_to_cart
自定义.php
foreach($result as $res) {
if( isset($_POST['bookwrap_type_name']) && ! empty($_POST['bookwrap_type_name']) )
$custom_data['custom_data']['field_wrap_name'] = $res[1];
if( isset($_POST['bookwrap_type_img']) && ! empty($_POST['bookwrap_type_img']) )
$custom_data['custom_data']['field_wrap_img'] = $res[2];
WC()->cart->add_to_cart($res[0], '1', '0', array(), $custom_data );
}
并显示在购物车和订单功能.php
function display_custom_data_in_cart($item_data, $cart_item)
{
if (isset($cart_item['custom_data'])) {
if (isset($cart_item['custom_data']['field_wrap_name']) && !empty($cart_item['custom_data']['field_wrap_name'])) {
$item_data[] = array(
'key' => __('Type of wrapper', 'theme-child'),
'value' => $cart_item['custom_data']['field_wrap_name'],
);
}
if (isset($cart_item['custom_data']['field_wrap_img']) && !empty($cart_item['custom_data']['field_wrap_img'])) {
$item_data[] = array(
'key' => __('An example of a cover', 'theme-child'),
'value' => '<img src="' . $cart_item['custom_data']['field_wrap_img'] . '" class="bwrap-cart-img">',
);
}
}
return $item_data;
}
add_filter('woocommerce_get_item_data', 'display_custom_data_in_cart', 10, 2);
它可以工作,然后我添加新产品,如何添加这个 $custom_data 然后在 custom.php 中的购物车中添加产品?
if( in_array( $res[0], array_column( WC()->cart->get_cart(), 'product_id' ) ) ) {
// product in cart
???
} else {
WC()->cart->add_to_cart($res[0], '1', '0', array(), $custom_data );
}
如果产品已经在购物车中,并且“custom_data”相同,您可以使用
WC_Cart
set_quantity()
方法,例如:
if( in_array( $res[0], array_column( WC()->cart->get_cart(), 'product_id' ) ) ) {
// Loop through cart items to get the cart item key
foreach ( WC()->cart->get_cart() as $item_key => $item ) {
if ( $item['product_id'] == $res[0] ) {
WC()->cart->set_quantity( $item_key, $item['quantity']+1 );
break;
}
}
} else {
WC()->cart->add_to_cart($res[0], '1', '0', array(), $custom_data );
}
应该可以。