D
D
Dmitry2016-01-07 16:16:59
PHP
Dmitry, 2016-01-07 16:16:59

How to get the number of items from the cart in Woocommerce by id?

Hello.
Tell me how in Woocommerce you can get the number of products in the cart, on the store page, knowing the id of each product.
Have a function

woocommerce_quantity_input( $args = array( 'input_value'   =>  0 ) );

It looks something like
5a397b90da18445aab7c7d854226c7d0.jpg
this. At the moment, I am passing 0 to the input field. And I want to transfer the number of goods from the basket. There is a product id.
Those. I'm looking for a function like:
$получить_количество_товаров_в_корзине( $id_товара );

And I want to get this
73f6c816683f455aa2e2a91e078124ef.jpg
. I hope I explained it clearly. Thank you all in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2016-01-08
@tosky

Mustafo, thanks for your reply. Here's a function I wrote in case it's useful to someone.

function erd_get_cnt_products( $product_id ) {
    $cart_content = WC()->cart->cart_contents;

    $cnt_products = 0;
    if ( $cart_content ) {
        foreach ( $cart_content as $cart_item ) {
            if ( $cart_item['product_id'] == $product_id ) {
                $cnt_products += $cart_item['quantity'];
            }
        }
    }

    return $cnt_products;
}

Now I call the function like this:
woocommerce_quantity_input( $args = array( 'input_value'   =>  erd_get_cnt_products( $product->id ) ) );

Although it seems to me that in Woocommerce this can be obtained in one line.

M
mustafo, 2016-01-07
@mustafo

Try like this:

global $woocommerce;
$items = $woocommerce->cart->get_cart();

Here, the $items array should contain all the information about the items in the cart. In my field 'quantity' is what you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question