A client of mine wanted to show out of stock products on a separate page – so I coded a simple shortcode for you all!

You can use this shortcode for different goals. For example, you might want to display what products you’ve sold to enhance customer trust / social proof.

So let’s see (1) how to create a shortcode and (2) how to take advantage of the existing [products] WooCommerce shortcode and its “ids” parameter to pass just those product IDs that are out of stock!

WooCommerce: Show Out of Stock Products via a Shortcode

PHP Snippet: Display Out of Stock Products via a Shortcode – WooCommerce

After you add the PHP below to your website, you can use the shortcode “out_of_stock_products” (see image) on any page.

In order for this to work, “Hide out of stock items from the catalog” must be disabled in the WooCommerce settings, otherwise the shortcode will return nothing.

/**
 * @snippet       Display All Products Out of Stock via a Shortcode - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    Woo 3.8
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
  
add_shortcode( 'out_of_stock_products', 'bbloomer_out_of_stock_products_shortcode' );
  
function bbloomer_out_of_stock_products_shortcode() {

	$args = array(
		'post_type' => 'product',
		'posts_per_page' => -1,
		'post_status' => 'publish',
		'meta_query' => array(
			array(
				'key' => '_stock_status',
				'value' => 'outofstock',
			)
		),
		'fields' => 'ids',
	);
	
	$product_ids = get_posts( $args ); 
	$product_ids = implode( ",", $product_ids );
	
	return do_shortcode("[products ids='$product_ids']");

}
Share:

Leave a Reply