每当woocommerce上的产品x出现在购物车中时,我都试图自动添加产品y(免费)。
我可以将一个产品x的代码ok放在购物篮中,另一个在购物车中自动显示为0(免费)。
但是我该如何自动将产品x(由客户选择)的数量与免费产品的数量(应该相同)相关联。
我想我有一个循环要做,并且与此功能相关 $ woocommerce->购物车-> set_quantity(product_id,product_quantity);
但是我在今天进行的所有测试和研究之间有些失落,进展不顺利
你能帮忙吗? ty aurelie
<?php
//Add free product to cart based on date and products in cart
add_action( 'template_redirect', 'add_product_to_cart' );
add_action( 'woocommerce_before_calculate_totals', 'add_product_to_cart' );
function add_product_to_cart() {
$dt = new DateTime();
$current_date = $dt->format('d/m/Y');
$end_promo = date('d/m/Y', '01/08/2019');
$product_id = 245; //free product
$anti_eau_id = 192; //product x who determined the offer
$allowed_products = array(245, 192); //all the product concerned by the offer
$found = false; //is free in basket ?
//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->id == $product_id ){
$found = true;
} elseif ( $_product->id == $anti_eau_id ){
$found = false;
} else {
$found = true;
}
}
// if products not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
//is product is in autorized list
if ( in_array( $_product->id, $allowed_products )){
if ( $_product->id == 245 && sizeof( WC()->cart->get_cart() ) >= 1){
$custom_price = 0; // This will be your custome price
$_product->set_price( $custom_price );
}
} else {
echo '1 offert pour 1 acheté';
}
}
}
}