Wordpress / WooCommerce - 基于类别自动添加多个优惠券

时间:2016-08-04 00:01:42

标签: php wordpress woocommerce discount

我在结帐时自动将优惠券添加到购物车中。基本上;如果存在类别A和B,则应用优惠券。如果优惠券已应用并且两个类别不再存在(客户从购物车中删除了商品),则删除优惠券。

这很有效,但我无法设置我真正想要的更进一步:

如果购物车中的商品A和商品B都适用购物车中的每件商品A的折扣。所以如果你有5个产品A应用折扣5次。如果客户随后删除了一个产品A,则删除已应用的额外优惠券。

我将如何实现这一目标?这是匹配和应用折扣的当前代码:

global $woocommerce;

    //create empty category array for push
    $category_array = [];
    // coupon code created in wooCommerce to apply
    $discount = 'A-bought-with-B';

    // start of the loop that fetches the cart items
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {

        $_product = $values['data'];
        $terms = get_the_terms( $_product->id, 'product_cat' );

        // find product categories and push them to the array
        foreach ($terms as $term) {
            $_categoryid = $term -> name;
            $category_name = strtolower( $_categoryid );

            // push term name to category array
            $category_array[] = $category_name;
        }
    }

    // 01
    // A Discount when purchased with B
    if ( in_array("A", $category_array) && in_array("B", $category_array) ) {

        $woocommerce->cart->add_discount( sanitize_text_field( $discount ) );

    } // if categories are not in cart, but the coupon is applied remove it
    else if ( !in_array("A", $category_array) || !in_array("B", $category_array) && $woocommerce->cart->has_discount( $sticker_coupon_code )  ) {
        $woocommerce->cart->remove_coupon( $discount );
    }

0 个答案:

没有答案