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!
PHP Snippet: Shortcode to Display WooCommerce In Stock Products Only
/**
* @snippet Display In Stock Products via Shortcode - WooCommerce
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 7
* @community https://businessbloomer.com/club/
*/
add_shortcode( 'in_stock_products', 'bbloomer_in_stock_products_shortcode_maybe_cat' );
function bbloomer_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']");
}
Hello, is it possible to highlight in stock variations on product page, where out of stock variations are available for pre-order? Flatsome theme.
Would this work? https://www.businessbloomer.com/woocommerce-display-variations-name-stock-shop-page/
Hi Rodolfo,
Thank you for all your work. Is there a code to show products marked as “Out of Stock” from the dropdown menu at the WooCmmerce /shop filter where you also see “sort by Latest” and “Sort by Popularity,” etc.?
Thank you,
Ozy
Hello Ozy, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!