【问题标题】:WooCommerce buy one get one 50% off, excluding a product variationWooCommerce 买一送一 50% 折扣,不包括产品变化
【发布时间】:2020-11-12 02:10:13
【问题描述】:

我使用 WooCommerce discount: buy one get one 50% off with a notice 回答代码,如果客户购买特定产品,客户在第二件商品上可获得 50% 的折扣。

现在,如果目标产品 id 是具有例如 3 个变体“A”、“B”和“C”的可变产品,我如何从折扣计算中排除变体“A”?这个条件应该放在哪里?

【问题讨论】:

  • 当您询问您的代码是使用现有答案代码生成的问题时,请始终在相关链接中提及它......现在您的问题不清楚:“如果变体 id = 不允许折扣. 条件应该放在哪里? ... 变体 ID 如何向您显示“不允许折扣”?你什么意思?

标签: php wordpress woocommerce cart discount


【解决方案1】:

以下将处理变体排除from the original answer代码:

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 文件中。经过测试并且可以工作。

【讨论】:

  • @gulfopticswebmaster 所以它现在可以工作了……如果是这种情况,请删除那些旧的 cmets。谢谢。
  • 上述代码变体id添加到$excl_variations_ids=array(41, 42);正在执行折扣
猜你喜欢
  • 1970-01-01
  • 2018-02-26
  • 2018-03-08
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
相关资源
最近更新 更多