Woocommerce中基于产品类别的第二项的数量折扣 [英] Quantity Discount for 2nd Item Based on Product Category in Woocommerce

查看:64
本文介绍了Woocommerce中基于产品类别的第二项的数量折扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于 仅对Woocommerce中的第二个项目提供数量折扣 回答我以前的一个问题,我想为如何为 has_term()添加if语句提供帮助那样,使此代码仅适用于一个或多个类别。

based on "Quantity discount on 2nd item only in Woocommerce" answer code to one of my pervious questions, I would like help on how to add a if statement for has_term() and that way, make this code applicable only for one or more categories.

任何曲目都会受到赞赏。

Any track will be appreciated.

推荐答案

以下内容将使用WordPress has_tem()条件函数来扩展已定义产品类别的代码:

The following will extend your code for defined product categories using WordPress has_tem() conditional function:

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

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

    $percentage = 20; // 20%
    $categories = array('cat1', 'cat2'); // Defined product categories term slugs
    $discount   = 0;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // When quantity is more than 1 and for defined product categories
        if( $cart_item['quantity'] > 1 && has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
            // 20% of the product price as a discount
            $discount += wc_get_price_excluding_tax( $cart_item['data'] ) * $percentage / 100;
        }
    }
    if( $discount > 0 )
        $cart->add_fee( __( '2nd item discount', 'woocommerce' ) , -$discount );
}

代码进入活动子主题(或活动主题)的function.php文件)。经过测试,可以正常工作。

Code goes in function.php file of your active child theme (or active theme). Tested and works.

这篇关于Woocommerce中基于产品类别的第二项的数量折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆