亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

WooCommerce 買一送一 50% 折扣,不包括產品變體

WooCommerce 買一送一 50% 折扣,不包括產品變體

PHP
largeQ 2023-08-19 17:46:54
我正在使用WooCommerce 折扣:買一送一 50% 折扣,并附有通知答案代碼,如果客戶購買特定產品,客戶在第二件商品上可享受 50% 折扣?,F在,如果目標產品 ID 是可變產品,例如具有 3 個變體“A”、“B”和“C”,那么如何從折扣計算中排除變體“A”?這個條件應該放在哪里呢?
查看完整描述

1 回答

?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

以下

add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_2nd_at_50', 10, 1 );

function add_custom_discount_2nd_at_50( $cart ){

? ? if ( is_admin() && ! defined( 'DOING_AJAX' ) )

? ? ? ? return;


? ? // YOUR SETTINGS:

? ? $variable_product_id = 40; // <== HERE your targeted variable product ID

? ? $excl_variations_ids = array( 41, 42); // <== HERE your variations to be excluded


? ? // Initializing variables

? ? $discount = $qty_notice = 0;

? ? $items_prices = array();


? ? // Loop through cart items

? ? foreach ( $cart->get_cart() as $key => $cart_item ) {

? ? ? ? if( $variable_product_id == $cart_item['product_id'] && in_array( $cart_item['variation_id'], $excl_variations_ids ) ) {

? ? ? ? ? ? $quantity = (int) $cart_item['quantity'];

? ? ? ? ? ? $qty_notice += $quantity;

? ? ? ? ? ? for( $i = 0; $i < $quantity; $i++ ) {

? ? ? ? ? ? ? ? $items_prices[] = floatval( $cart_item['data']->get_price());

? ? ? ? ? ? }

? ? ? ? }

? ? }


? ? $count_items = count($items_prices); // Count items


? ? rsort($items_prices); // Sorting prices descending order


? ? if( $count_items > 1 ) {

? ? ? ? foreach( $items_prices as $key => $price ) {

? ? ? ? ? ? if( $key % 2 == 1 )

? ? ? ? ? ? ? ? $discount -= number_format( $price / 2, 2 );

? ? ? ? }

? ? }


? ? // Applying the discount

? ? if( $discount != 0 ){

? ? ? ? $cart->add_fee('Buy one get one 50% off' ,$discount? ); // true


? ? ? ? // Displaying a custom notice (optional)

? ? ? ? wc_clear_notices(); // clear other notices on checkout page.

? ? ? ? if( ! is_checkout() ){

? ? ? ? ? ? wc_add_notice( __("You get 50% of discount on the 2nd item"), 'notice');

? ? ? ? }

? ? }

? ? //? Display a custom notice on cart page when quantity is equal to 1.

? ? elseif( $qty_notice == 1 ){

? ? ? ? wc_clear_notices(); // clear other notices on checkout page.

? ? ? ? if( ! is_checkout() ){

? ? ? ? ? ? wc_add_notice( __( "Add one more to get 50% off on 2nd item" ), 'notice');

? ? ? ? }

? ? }

}

代碼位于活動子主題(或活動主題)的functions.php 文件中。經過測試并有效。


查看完整回答
反對 回復 2023-08-19
  • 1 回答
  • 0 關注
  • 163 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號