Search code examples
phpwordpresswoocommerceshortcodeelementor

How do I create a "sold" page that automatically displays any out of stock products?


I am in the process of building my woo commerce store using wordpress and elementor but I've run into a wall as I don't know how (or if it's possible) to create a "sold" page that automatically showcases all of my sold listings based on their out of stock status--essentially creating a gallery/portfolio to help build customer trust.

I've tried adding a couple variations of code that I found online to my theme files, notably:

/**
 * @snippet       Display Out of Stock Products via Shortcode - WooCommerce
 * @how-to        businessbloomer.com/woocommerce-customization
 * @author        Rodolfo Melogli, Business Bloomer
 * @compatible    WooCommerce 5
 * @community     https://businessbloomer.com/club/
 */
   
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']");
 
}

But instead of showing my sold listings, this led to no results when I tried to use the shortcode to a container on my sold page, I believe I used

[products limit="6" columns="3" out_of_stock_products="true"].

Any help would be appreciated, Thank you!!


Solution

  • This can be solved simply using woocommerce_shortcode_products_query filter hook.

    So if you are created a custom page "Sold", you will have to define the desired page ID, title, or slug inside is_page() WordPress conditional function, to restrict the behavior to that page only, with "products" shortcode usage.

    The code:

    add_filter( 'woocommerce_shortcode_products_query', 'products_shortcode_outofstock', 10, 3);
    function( $query_args, $attributes, $type ){
        // Define below the desired Page ID, slug or title
        if( is_page( 'sold' ) && $type === 'products' ){
            $query_args['meta_query'] = array( array(
                'key'     => '_stock_status',
                'value'   => 'outofstock',
                'compare' => '=',
            ) );
        }
        return $query_args;
    }
    

    Code goes in functions.php file of your active child theme (or theme) or also in any plugin file.

    Then on that "Sold" page, you can use the "products" shortcode normally like:

    [products limit="-1" columns="3" paginate="true"]
    

    It will display only out-of-stock products.

    Related and references: