php - 基于购物车商品数量的购物车折扣,仅适用于非促销商品

标签 php wordpress woocommerce cart discount

在 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);
} 

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

谢谢。

最佳答案

这是一个自定义 Hook 函数,如果购物车中有 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 文件中或任何插件文件中。

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

关于php - 基于购物车商品数量的购物车折扣,仅适用于非促销商品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767754/

相关文章:

wordpress - 哪个 CMS 使用 ORM(对象关系映射)

javascript - Axios Put 请求在 Vue.js 中给出 404 错误

php - 为什么 fetch_all 语句之后的 fetch 语句没有任何值?

php - 如何停止搜索返回所有结果?

html - 标题中的电话号码不可点击

php - 在 Woocommerce 3 中通过 ajax 提交并创建结帐订单

php - 替换 woocommerce 标题

php - Mysql 搜索表查找日期时间字段并更改时区

php - PHP中判断表格每一行的CheckBox是否被选中

php - 在 Zend Framework 中加载 Wordpress 函数