Home » WooCommerce: In Stock Products Shortcode

WooCommerce: In Stock Products Shortcode

by Tutor Aspire

We’ve already coded a solution to display WooCommerce out of stock products only via a custom shortcode – today we’ll do the opposite: how can we display in stock products only via a handy shortcode?

Once again, the solution “gets” the list of products IDs that are in stock, and then passes the result to the official [products] WooCommerce shortcode, so that we don’t reinvent the wheel.

You can then use the [in_stock_products] shortcode anywhere you wish – on a blog post, in a custom page, in a widget, and so on. You can even customize the output with the official WooCommerce [products] shortcode parameters such as columns, orderby, limit, etc. Enjoy!

On this custom WordPress page, the [in_stock_products] shortcode outputs the list of… in stock products!

PHP Snippet: Shortcode to Display WooCommerce In Stock Products Only

/**
 * @snippet       Display In Stock Products via Shortcode - WooCommerce
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 7
 * @donate $9     https://www.tutoraspire.com
 */

add_shortcode( 'in_stock_products', 'tutoraspire_in_stock_products_shortcode_maybe_cat' );
   
function tutoraspire_in_stock_products_shortcode_maybe_cat() {

$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'instock',
)
),
'fields' => 'ids',
);

$product_ids = get_posts( $args ); 
$product_ids = implode( ",", $product_ids );

return do_shortcode("[products ids='$product_ids']");
 
}

You may also like