特定Woocommerce产品类别项目的强制性优惠券代码

时间:2018-04-11 00:45:16

标签: php wordpress woocommerce custom-taxonomy coupon

在Woocommerce中,我正在尝试为特定类别的所有产品制定优惠券代码。

以下代码(位于functions.php中)效果很好,但无论产品类别如何,所有产品都必须使用优惠券代码:

add_action('woocommerce_check_cart_items', 'make_coupon_code');

function make_coupon_code()
{
    global $woocommerce;
    if(is_cart() || is_checkout()){
        $my_coupon = $woocommerce->cart->applied_coupons;
        echo $woocommerce->cart->get_applied_coupons;
        if(empty($my_coupon))
        {
            wc_add_notice( '<strong>' . $btn['label'] . '</strong> ' . __( 'insert coupon code', 'woocommerce' ), 'error' );
        }
    }
}

有什么想法吗?

(我试图定位的产品类别是'chef-masterclass')

1 个答案:

答案 0 :(得分:0)

更新:以下代码可防止结帐需要应用于特定产品类别的强制性优惠券代码:

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code' );
function mandatory_coupon_code() {
    // HERE below -- Your settings
    $mandatory_coupon   = 'summer'; // <== Coupon code
    $product_categories = array( 'chef-masterclass' ); // <== Product category (Id, slug or name)

    $applied_coupons = WC()->cart->get_applied_coupons();

    // If coupon is found we exit
    if( in_array( $mandatory_coupon, $applied_coupons ) ) return;

    $found = false;

    // Loop through cart items to check for the product category
    foreach ( WC()->cart->get_cart() as $cart_item ){
        if( has_term( $product_categories, 'product_cat', $cart_item['product_id'] ) ){
            $found = true; // cart item from the product category is found
            break; // We can stop the loop
        }
    }

    // Coupon not applied and product category found
    if( $found ){
        // Display an error notice preventing checkout
        $coupon_html = '<strong>"' . ucfirst( $mandatory_coupon ) . '"</strong>';
        $message = sprintf( __( 'Please enter the coupon code %s to checkout.', 'woocommerce' ), $coupon_html );
        wc_add_notice( $message, 'error' );
    }
}

代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作