Checking products in cart based on category name woocommerce?

前端 未结 2 1063
爱一瞬间的悲伤
爱一瞬间的悲伤 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:40

    @Guillaume and others who helped- thanks for posting this for it was helpful to me. Once I started testing I realized that the code didn't work for all of my products. Some products in my case have categories with sub-categories and that was preventing the code from picking up the relevant categories on all the products. I altered your code slightly to create an array and it seems to be working well:

    function check_product_in_cart() {
        //Check to see if user has product in cart
        global $woocommerce;
    
        // 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
            // this is where I started editing Guillaume's code
    
            $cat_ids = array();
    
            foreach ($terms as $term) {
                $cat_ids[] = $term->term_id;
            }
    
            if(in_array(434, (array)$cat_ids) || in_array(435, (array)$cat_ids)) {
    
              //category is in cart!
               $product_in_cart = true;
            }
        }
    
        return $product_in_cart;
    }
    

提交回复
热议问题