所以最后,我找到了我的问题的解决方案。
当通过函数从会话加载购物车时出现问题get_cart_from_session()
from class-wc-cart.php
.
当额外的密钥添加到购物车项目时,我们需要通过以下方式注入密钥woocommerce_get_cart_item_from_session
filter.
用户现在可以选择追加销售,该追加销售会在添加产品的同时自动添加到购物车。我还有一个功能,如果主要产品被删除,我可以删除追加销售。
这是我添加到functions.php中的最终代码:
/**
* Add upsells as extra data for added product
*/
function add_upsells_to_cart( $cart_item_key ) {
global $woocommerce;
if ( empty( $_REQUEST['upsells'] ) || ! is_array( $_REQUEST['upsells'] ) )
return;
// Prevent loop
$upsells = $_REQUEST['upsells'];
unset( $_REQUEST['upsells'] );
// Append each upsells to product in cart
foreach( $upsells as $upsell_id ) {
$upsell_id = absint( $upsell_id );
// Add upsell into cart and set upsell_of as extra key with parent product item id
$woocommerce->cart->add_to_cart( $upsell_id, 1, '', '', array( 'upsell_of' => $cart_item_key ) );
}
}
add_action( 'woocommerce_add_to_cart', 'add_upsells_to_cart', 1, 6 );
/**
* Inject upsell_of extra key cart item key when cart is loaded from session
*/
function get_cart_items_from_session( $item, $values, $key ) {
if ( array_key_exists( 'upsell_of', $values ) )
$item[ 'upsell_of' ] = $values['upsell_of'];
return $item;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'get_cart_items_from_session', 1, 3 );
/**
* Remove associated upsells if product removed from cart
*/
function remove_upsells_from_cart( $cart_item_key ) {
global $woocommerce;
// Get cart
$cart = $woocommerce->cart->get_cart();
// For each item in cart, if item is upsell of deleted product, delete it
foreach( $cart as $upsell_key => $upsell )
if ( $upsell['upsell_of'] == $cart_item_key )
unset( $woocommerce->cart->cart_contents[ $upsell_key ] );
}
add_action( 'woocommerce_before_cart_item_quantity_zero', 'remove_upsells_from_cart' );