skip to Main Content

Is there a way to get the number of items of a specific product by its id? For example, I added to my cart 5 green apples and 10 lemons. I want to get the number of green apples in cart (which is 5), by the id of the green apple product.

Is there a simple way to achieve? Thanks

2

Answers


  1. Chosen as BEST ANSWER

    Ok I cracked it:

    $cartId = WC()->cart->generate_cart_id( PRODUCT_ID);
    $cartItemKey = WC()->cart->find_product_in_cart( $cartId );
    $startingVal = WC()->cart->get_cart_contents()[$cartItemKey]["quantity"];
    

  2. You can use the following function to get product quantity of a particular product

    $quantity = '';
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if( $cart_item['product_id'] == 'your_id_here'){
            $quantity = $cart_item['quantity'];
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search