We currently have a cart found dd tag that shows the quantity input for an item. I would like to have something that displays just the output of the text of what’s in the cart. The idea is to create my own mini-cart without relying on the mini-cart element so that I have more control but this is the only piece I’m missing.
1 Like
Hi maybe this will help you Cart (WooCommerce) – Bricks Academy
Unfortunately this provides the quantity input field from the cart page, nothing here just outputs the number.
I can get the total count of all items in the cart, but I can get the quantity of individual items. This is the only thing missing from being able to make my own mini cart set up
Well this may help with that:
function get_product_quantity($atts) {
// Extract the attributes, defaulting to product ID 0 if not provided
$atts = shortcode_atts(array(
'id' => "0",
), $atts, 'quantity');
$product_id = $atts['id'];
$total_quantity = 0;
// Get the cart object
$cart = WC()->cart;
// Loop through the cart items
foreach ($cart->get_cart() as $cart_item) {
// Check if the product ID matches the target product ID
if ($cart_item['product_id'] == $product_id || $cart_item['variation_id'] == $product_id) {
// Accumulate the quantity
$total_quantity += $cart_item['quantity'];
}
}
return $total_quantity;
}
Adjust as needed
had to make a few changes, I think I was getting a syntax error
function get_product_quantity_shortcode($atts) {
return get_product_quantity($atts);
}
add_shortcode('product_quantity', 'get_product_quantity_shortcode');
function get_product_quantity($atts) {
$atts = shortcode_atts(array(
'id' => 0,
), $atts, 'quantity');
$product_id = $atts['id'];
$total_quantity = 0;
$cart = WC()->cart;
if ( $cart ) {
foreach ($cart->get_cart() as $cart_item) {
if ($cart_item['product_id'] == $product_id || $cart_item['variation_id'] == $product_id) {
$total_quantity += $cart_item['quantity'];
}
}
}
return $total_quantity;
}
The shortcode would be [product_quantity id=“{post_id}”]