Home » WooCommerce: Display Variations’ Stock @ Shop Page

WooCommerce: Display Variations’ Stock @ Shop Page

by Tutor Aspire

Thanks to the various requests I get from Business Bloomer fans, this week I’m going to show you a simple PHP snippet to echo the variations’ name and stock quantity on the shop, categories and loop pages.

Of course, if “Manage stock” is not enabled at variation level, the quantity will be null, and therefore the returned string will just say “In stock” or “Out of stock”.

Enjoy!

Show the stock status of each variation for variable products on the WooCommerce Shop page

PHP Snippet: Display Variations’ Name & Stock @ WooCommerce Loop Pages

/**
 * @snippet       Display Variations' Stock @ WooCommerce Shop
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @testedwith    WooCommerce 5
 * @donate $9     https://www.tutoraspire.com
 */
 
add_action( 'woocommerce_after_shop_loop_item', 'tutoraspire_echo_stock_variations_loop' );
   
function tutoraspire_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 '
' . implode( ', ', $attr_string ) . ': ' . $stock_string; } } }

You may also like