WooCommerce product shortcode – stock products only
In WooCommerce, to display only in-stock products using a shortcode, you can use the [products]
shortcode with additional parameters to filter the products. Unfortunately, the default WooCommerce shortcodes do not provide a direct way to filter by stock status. However, you can achieve this with a custom shortcode.
Here’s how you can create a custom shortcode to display only in-stock products:
- Add the Custom Shortcode to Your Theme’s
functions.php
File:Add the following code to your theme’sfunctions.php
file. This code creates a new shortcode[in_stock_products]
that queries and displays only in-stock products.function in_stock_products_shortcode($atts) { ob_start(); // Define default attributes $atts = shortcode_atts(array( 'limit' => '10', // Default limit to 10 products 'columns' => '4', // Default to 4 columns ), $atts, 'in_stock_products'); // WP_Query arguments $args = array( 'post_type' => 'product', 'posts_per_page' => $atts['limit'], 'post_status' => 'publish', 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', ), ), ); // Query products $loop = new WP_Query($args); // Check if there are products if ($loop->have_posts()) { echo '
- ';
while ($loop->have_posts()) : $loop->the_post();
wc_get_template_part('content', 'product');
endwhile;
echo '
Use the Custom Shortcode in Your Posts or Pages
Now you can use the custom shortcode
[in_stock_products]
in your posts or pages. You can also specify the number of products to display and the number of columns:[in_stock_products limit="12" columns="3"]
This example will display 12 in-stock products in 3 columns. Adjust the
limit
andcolumns
attributes as needed for your specific requirements.Summary
- Add the provided PHP code to your theme’s
functions.php
file. - Use the
[in_stock_products]
shortcode in your content to display only in-stock products. - Customize the
limit
andcolumns
attributes to fit your layout needs.
- Add the provided PHP code to your theme’s