Skip to content
Advertisement

Set a max displayed available stock quantity on Woocommerce archives for variable products

I want to set the maximum number of stock available items on Woocommerce shop pages.

I am using Display the stock availability for all product types in Woocommerce archive pages answer code, which does a great job, showing the available stock for variations in a Woocommerce shop.

But I want to show a maximum number, say 50, if the stock is actually in excess of 50. If there are 721 of an item in stock, I just want the number to show 50 to the customer.

I tried to add another if statement to the existing code but it simply added another line to the display, showing the actual total stock as well as my maximum number of 50, if the total was above 50.

Advertisement

Answer

The following that will limit the sock quantity display to 50 when it’s over 50, for variable products:

add_action( 'woocommerce_after_shop_loop_item', 'wc_loop_get_product_stock_availability_text', 10 );
function wc_loop_get_product_stock_availability_text() {
    global $wpdb, $product;

    $max_stock_qty = 50; // Maximum Number of Available Stock qty

    // For variable products
    if( $product->is_type('variable') ) {

        // Get the stock quantity sum of all product variations (children)
        $stock_quantity = $wpdb->get_var("
            SELECT SUM(pm.meta_value) FROM {$wpdb->prefix}posts as p
            JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
            WHERE p.post_type = 'product_variation'
            AND p.post_status = 'publish' AND p.post_parent = '".get_the_id()."'
            AND pm.meta_key = '_stock' AND pm.meta_value IS NOT NULL
        ");

        if ( $stock_quantity > 0 ) {
            // Here we limit the sock quantity display to 50 when it's up to 50
            $stock_quantity = $stock_quantity >= $max_stock_qty ? $max_stock_qty : $stock_quantity;
            
            echo '<p class="stock in-stock">'. sprintf( __("%s in stock", "woocommerce"), $stock_quantity ).'</p>';
        } else {
            if ( is_numeric($stock_quantity) )
                echo '<p class="stock out-of-stock">' . __("Out of stock", "woocommerce") . '</p>';
            else
                return;
        }
    }
    // Other products types
    else {
        echo wc_get_stock_html( $product );
    }
}

Code goes in functions.php file of your active child theme (or active theme). It should work works.

Related: Display the stock availability for all product types in Woocommerce archive pages

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement