【问题标题】:Cart discount based on cart item count and only for items that are not in sale基于购物车商品数量的购物车折扣,仅适用于非销售商品
【发布时间】:2017-06-05 16:25:53
【问题描述】:

在 WooCommerce 中,我想专门为那些不销售的产品提供 10% 的折扣。如果购物车商品数量为 5 件或更多商品且未在售,则我给予 10% 的折扣。

我在这里使用以下代码根据购物车商品数量限制获得折扣:

add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');

/**
* Add custom fee if more than three article
* @param WC_Cart $cart
*/

function add_custom_fees( WC_Cart $cart ){
     if( $cart->cart_contents_count < 5 ){
         return;
     } 
    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.1;
    $cart->add_fee( '10% discount', -$discount);
} 

但我不知道如何仅对非销售商品应用折扣。我怎样才能实现它?

谢谢。

【问题讨论】:

  • more than 5 products 等于 $cart-&gt;cart_contents_count &lt;= 5
  • 您有问题吗?这行得通吗?到底是什么问题?
  • 我认为你最好在 Code Review 上询问。
  • @H.Pauwelyn 好心,这个问题就在 StackOverFlow 上……谢谢。

标签: php wordpress woocommerce cart discount


【解决方案1】:

这是一个自定义挂钩函数,如果购物车中有 5 件或更多商品且没有产品在售,则该函数将应用于购物车折扣

add_action('woocommerce_cart_calculate_fees' , 'custom_discount', 10, 1);
function custom_discount( $cart ){

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Only when there is 5 or more items in cart
    if( $cart->get_cart_contents_count() >= 5):

        // Initialising variable
        $is_on_sale = false;

        // Iterating through each item in cart
        foreach( $cart->get_cart() as $cart_item ){
            // Getting an instance of the product object
            $product =  $cart_item['data'];

            // If a cart item is on sale, $is_on_sale is true and we stop the loop
            if($product->is_on_sale()){
                $is_on_sale = true;
                break;
            }
        }

        ## Discount calculation ##
        $discount = $cart->subtotal * -0.1;

        ## Applied discount (no products on sale) ##
        if(!$is_on_sale )
            $cart->add_fee( '10% discount', $discount);

    endif;
}

此代码位于您的活动子主题(或主题)的 function.php 文件中或任何插件文件中。

这段代码已经过测试并且可以完美运行。

【讨论】:

  • 如何针对特定类别进行购物车折扣? @LoicTheAztec
  • @mysticalghoul 我有东西……给我发消息
猜你喜欢
  • 2019-01-31
  • 2017-09-27
  • 2020-08-18
  • 1970-01-01
  • 2019-02-06
  • 2015-06-01
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多