Reputation: 5483
I want to show the stock status for every product in cart with the status "few in stock".
Like this:
Productname
Size: L
Only 4 left <- this is new
I found a snippet to show the stock status on shop pages:
add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_show_stock_shop', 10 );
function bbloomer_show_stock_shop() {
global $product;
echo wc_get_stock_html( $product );
}
Source: https://businessbloomer.com/woocommerce-add-stock-quantity-on-shop-page/
I tried to change the hook from woocommerce_after_shop_loop_item
to woocommerce_after_cart_item_name
to display the status below the title in the cart.
But the snippet doesn't work.
Also I have no idea how to limit it to items with a low stock.
Upvotes: 0
Views: 2760
Reputation: 21681
please try below code in function.php file
add_filter( 'woocommerce_cart_item_name', 'showing_stock_in_cart_items', 99, 3 );
function showing_stock_in_cart_items( $item_name, $cart_item, $cart_item_key ) {
// The WC_Product object
$product = $cart_item['data'];
if (empty($product)) {
return $item_name;
}
// Get the stock
$stock = $product->get_stock_quantity();
// When stock doesn't exist
if (empty($stock)) {
return $item_name;
}
// display the stock
if ($stock <= '50') :
$item_name .='<br><p style="color:green;" class="product-stock">'.__( "only " .$stock. " left","woocommerce").'</p>';
endif;
return $item_name;
}
also refer action and filter hook:-documentation here
Upvotes: 3