Reputation: 33
I'm trying to create a custom WooCommerce shortcode (with a 'product id' attribute in the shortcode) that will display the current quantity that the customer currently has in their cart of that particular item.
I have a good start and my shortcode is displaying correctly for single/simple products, but there's an issue when it comes to products that have multiple variations. I'd like the shortcode to show the total number for the parent product; it's not necessary to show quantities for each variation.
For example, if the customer's cart has:
I want the shortcode to show 6.
I thought that I could do this by using WC()->cart->get_cart()
and making sure to use $cart_item['product_id']
instead of $cart_item['variation_id']
but despite the fact that I'm using 'product id' and the shortcode attribute is the id of the parent product, it's only showing the cart quantity for whatever variation was added to the cart most recently.
Any ideas on how I can tweak this to show the in-cart sum of all variations underneath the parent product?
Here's my code that I have so far:
if( !function_exists('in_cart_product_quantity') ) {
function in_cart_product_quantity( $atts ) {
$atts = shortcode_atts(array('id' => ''), $atts, 'cart_qty_badge');
if( empty($atts['id'])) return;
if ( WC()->cart ) {
$qty = 0;
foreach (WC()->cart->get_cart() as $cart_item) {
if($cart_item['product_id'] == $atts['id']) {
$qty = $cart_item['quantity'];
}
}
return $qty;
}
return;
}
add_shortcode( 'cart_qty_badge', 'in_cart_product_quantity' );
}
Upvotes: 1
Views: 248
Reputation: 254363
Use the following instead, that should solve your issue when there are multiple variations for specific variable product in cart:
if( ! function_exists('get_product_quantity_in_cart') ) {
function get_product_quantity_in_cart( $atts ) {
// Extract shortcode attributes
extract( shortcode_atts( array(
'id' => '',
), $atts, 'cart_qty_badge' ) );
if( empty($id) || WC()->cart->is_empty() ) return;
$total_qty = 0;
foreach ( WC()->cart->get_cart() as $cart_item ) {
if( $cart_item['product_id'] == $id ) {
$total_qty += $cart_item['quantity'];
}
}
return $total_qty > 0 ? $total_qty : '';
}
add_shortcode( 'cart_qty_badge', 'get_product_quantity_in_cart' );
}
It should work.
Upvotes: 1