Checking products in cart based on category name woocommerce?

前端 未结 2 1060
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 03:06

I\'m trying to trigger an echo statement if a certain category of product is in my cart, here\'s my code:



        
2条回答
  •  既然无缘
    2020-12-17 03:50

    Edited my code following Barrell's advice and echo 'Bingo'!

    Works like a charm, here's the code:

        function check_product_in_cart() {
            //Check to see if user has product in cart
            global $woocommerce;
    
            //assigns a default negative value
            //  categories targeted 17, 18, 19
    
            $product_in_cart = false;
    
            // 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' );
    
                // second level loop search, in case some items have several categories
                foreach ($terms as $term) {
                    $_categoryid = $term->term_id;
                    if (( $_categoryid === 17 ) || ( $_categoryid === 18 ) || ( $_categoryid === 19 )) {
                        //category is in cart!
                        $product_in_cart = true;
                    }
                }
            }
    
            return $product_in_cart;
       }
    

    Hope that can help someone!

提交回复
热议问题