If you have products that tend to sell out, or that you typically sell in bulk, it might be beneficial to display the available product quantity. This can ensure your customers can order the quantity or volume they need.
Displaying your stock availability is as simple as adding a quick code snippet to your theme’s function.php file.
PHP Code Snippet via Image
Here is what the code snippet would look like (captured image of the actual code snippet):
PHP Code Snippet via Text
Here is what the code snippet would look like (copiable text string of the actual code snippet):
add_action( 'woocommerce_after_shop_loop_item', 'wc_echo_stock_variations_loop' );
function wc_echo_stock_variations_loop(){
global $product;
if ( $product->get_type() == 'variable' ) {
foreach ( $product->get_available_variations() as $key ) {
$variation = wc_get_product( $key['variation_id'] );
$stock = $variation->get_availability();
$stock_string = $stock['availability'] ? $stock['availability'] : __( 'In stock', 'woocommerce' );
$attr_string = array();
foreach ( $key['attributes'] as $attr_name => $attr_value ) {
$attr_string[] = $attr_value;
}
echo '<br/>' . implode( ', ', $attr_string ) . ': ' . $stock_string;
}
}
}
There is a straightforward code snippet that could be used for displaying stock status on variable products on the shop page in WooCommerce that is publicly available to the WooCommerce User Community on the following page:
https://www.businessbloomer.com/woocommerce-display-variations-name-stock-shop-page/
The Nexcess version of that code snippet that was used in the examples above for this article is found on the on the following page:
https://gist.github.com/lukecav/f399f606aa2a7a3b39a0e0331bd09b35
Happy customizing!
Get Started With Managed WooCommerce
Not a Nexcess customer yet? Check out our fully managed WooCommerce hosting plans to get started today.
Recent Articles
- Setup & Settings for the W3 Total Cache Plugin
- Best Mailchimp Alternatives for Email Marketing
- How to Use the Nexcess Client Portal API Token