【发布时间】:2021-09-13 17:06:24
【问题描述】:
我遇到了一个问题。此功能运行良好。但是现在我想在购物车中添加此产品454545 时,还需要在购物车中添加此263654 产品五次。如果我在购物车中添加常规/其他产品,则需要像以前一样将这个产品 263654 一次性添加到购物车中。
add_action('woocommerce_add_to_cart', 'add_product_to_cart');
function add_product_to_cart() {
if ( !is_admin() && !is_cart() && !is_checkout()) {
$product_id = 263654; //replace with your own product id
$specific_products = 454545;
$excloud_product = 380978;
$excloud_product1 = 446740;
$found = false;
$items_count = 0;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id || $_product->get_id() == $excloud_product ){
$product_key = $cart_item_key;
$product_qty = $cart_item['quantity'];
$found = true;
}else {
$items_count++;
}
}
// if product not found, add it
if ( ! $found ){
WC()->cart->add_to_cart( $product_id, $items_count );
}else{
WC()->cart->set_quantity( $product_key, $items_count );
}
}else{
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
【问题讨论】:
标签: php wordpress function woocommerce cart