Menu Close

WooCommerce: Display Out of Stock Products (Shortcode)

default

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] 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 Out of Stock Products via Shortcode - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 5
 * @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']");

}
View Source
Posted in WooCommerce Tips