Quantity Discount for 2nd Item Based on Product Category in Woocommerce

爷,独闯天下 提交于 2019-12-11 07:51:01

问题


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.


回答1:


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

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



来源:https://stackoverflow.com/questions/54271364/quantity-discount-for-2nd-item-based-on-product-category-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!