如果购物车中指定了变化,则将免费产品添加到购物车

时间:2020-05-19 22:51:13

标签: php wordpress woocommerce

我有这个代码

function woocustom_add_product_to_cart()
{
    if (!is_admin())
    {
        $product_id = 12345; // Product Id of the free product which will get added to cart
        $is_present = false;
        $cart = WC() - > cart - > get_cart();

        //check if product already in cart
        if (sizeof(WC() - > cart - > get_cart()) > 0)
        {
            foreach(WC() - > cart - > get_cart() as $cart_item_key => $values)
            {
                $_product = $values['data'];

                if ($_product - > get_id() == $product_id) {
                    $is_present = true;
                }
            }

            // if free product not found, add it
            if (!$is_present) {
                WC() - > cart - > add_to_cart($product_id);
            }
        }
    }
}   

add_action( 'woocommerce_add_to_cart', 'woocustom_add_product_to_cart', 10, 2 );

只有在购物车中指定了产品变体形式时,我该如何更改才能使此代码起作用?

0 个答案:

没有答案