Add WooCommerce coupon code automatically based on product categories

北战南征 提交于 2019-12-06 10:09:07

Here is the correct hook and code, that will auto apply a coupon code when a cart item is from specific product categories and will update cart totals:

add_action( 'woocommerce_before_calculate_totals', 'wc_auto_add_coupons_categories_based', 10, 1 );
function wc_auto_add_coupons_categories_based( $cart_object ) {

    // HERE define your product categories and your coupon code
    $categories = array('t-shirts-d','socks-d','joggers-d','boxers-d');
    $coupon = 'drawer';

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

    // Initialising variables
    $has_category = false;

    //  Iterating through each cart item
    foreach ( $cart_object->get_cart() as $cart_item ) {
        // If a cart item belongs to a product category
        if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
            $has_category = true; // Set to true
            break; // stop the loop
        }
    }

    // If conditions are matched add the coupon discount
    if( $has_category && ! $cart_object->has_discount( $coupon )){
        // Apply the coupon code
        $cart_object->add_discount( $coupon );

        // Optionally display a message 
        wc_add_notice( __('my message goes here'), 'notice');
    } 
    // If conditions are not matched and coupon has been appied
    elseif( ! $has_category && $cart_object->has_discount( $coupon )){
        // Remove the coupon code
        $cart_object->remove_coupon( $coupon );

        // Optionally display a message 
        wc_add_notice( __('my warning message goes here'), 'alert');
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Code is tested on woocommerce 3+ and works.

If the coupon has been applied and the cart items from specific product categories are all removed, the coupon is also removed.

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