Shahid Sarwar
Shahid Sarwar

Reputation: 1209

Get total number of products currently in cart passing the user ID

I am trying to figure out how to get total number of products currently in the cart. I would like to know if there is a woocommerce function that can fetch me the count of products in the cart by passing the user ID. I cannot find anything on the office documentation.

Please help me with this.

I tried this function but it only returns the total orders:

$i =  wc_get_customer_order_count($user_id);

And following a link I tried this too:

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

I am new to WordPress and I would also like to know how to initialize $woocommerce.

Upvotes: 3

Views: 1337

Answers (2)

samisonline
samisonline

Reputation: 188

To get this via Ajax so it updates when the total updates use this https://github.com/samisonline/ajax_cart

This has a cart counter, and separately a mini cart with details of each product

Upvotes: 0

LoicTheAztec
LoicTheAztec

Reputation: 253783

The answer is (without any need of $user_id or global $woocommerce):

$items_count = WC()->cart->get_cart_contents_count();

You will get the current customer cart items count.

There is NO user_id related to cart, as a non logged/registered user can add items in cart. So this will not work for cart.

Live cart is saved in session and current user has a corresponding cookie in his browser…

Upvotes: 3

Related Questions