我要在购物车总数大于25时自动向购物车中添加一种变化产品。自动添加变化产品价格需要设置为0,客户也不能更改数量或需要停用免费产品的数量。我在下面添加了代码,并且每次重新加载页面或购物车更新免费产品数量增加时,它只能正常工作的问题。我只想出售1数量的免费产品。怎么做 ?代码如下。
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 25;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( ! is_admin()) {
$free_product_id = 2696;
$variation_id = 2697;
$arr = array();
$arr['Color'] = 'Blue';// Product Id of the free product which will get added to cart
$found = false;
//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() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id,1,$variation_id,$arr );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id,1,$variation_id,$arr );
}
}
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
function add_custom_price( $cart_object ) {
$cart_total = 25; // If cart total is more than this value.
$free_product_id = 2697; // Set price to 0 of this free product.
$carttotal = 0;
foreach ( $cart_object->cart_contents as $key => $value ) {
$_product = $value['data'];
if ( $_product->get_id() == $free_product_id ){
continue;
}
$carttotal += $value['line_total'];
}
if ( $carttotal >= $cart_total ) {
$custom_price = 0; // This will be your custome price
foreach ( $cart_object->cart_contents as $key => $value ) {
$_product = $value['data'];
if ( $_product->get_id() == $free_product_id ){
$value['data']->set_price( $custom_price );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
add_filter( 'woocommerce_quantity_input_args', 'hide_quantity_input_field', 20, 2 );
function hide_quantity_input_field( $args, $product ) {
// Here set your product IDs in the array
$product_ids = array(2697);
// Handling product variation
$the_id = $product->is_type('variation') ? $product->get_variation_id() : $product->get_id();
//var_dump($the_id);
// Only on cart page for a specific product category
if( is_cart() && in_array( $the_id, $product_ids ) ){
$input_value = $args['input_value'];
$args['min_value'] = $args['max_value'] = $input_value;
}
return $args;
}
答案 0 :(得分:0)
尝试在functions.php
中添加以下代码,并替换为必需的product id
add_filter( 'woocommerce_add_to_cart_validation', 'allowed_products_variation_in_the_cart', 10, 5 );
function allowed_products_variation_in_the_cart( $passed, $product_id, $quantity, $variation_id, $variations) {
$product_b = 14091;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$cart_product_id = $cart_item['product_id'];
if ($cart_item['variation_id']) {
$cart_product_id = $cart_item['variation_id'];
}
if ( ( $variation_id == $product_b) ) {
wc_add_notice(__('You can\'t add this product.', 'domain'), 'error');
$passed = false; // don't add the new product to the cart
// We stop the loop
break;
}
}
return $passed;
}