phpwordpresswoocommerceshortcodeproduct

Display only "in stock" products in Woocommerce Recent Products shortcode


I need to exclude Out of Stock items from displaying when the Woocommerce Recent Products shortcode is used on my front page.

[recent_products]

Is it possible to create a rule like hide_outofstock="true" or something along those lines to stop Out of Stock products showing?

I have trawled the web looking for ideas on how to approach this problem, and I'm no coder at all but usually I'm able to frankenstein something to get around issues like this. However, right now I am stumped. All and any help will be much appreciated.


Solution

  • June 2018 Update (for product type compatibility)

    After a little search in WC_Shortcodes class source code, here is the proper way to do it:

    add_filter( 'woocommerce_shortcode_products_query', function( $query_args, $atts, $loop_name ){
        if( $loop_name == 'recent_products' ){
            $query_args['meta_query'] = array( array(
                'key'     => '_stock_status',
                'value'   => 'outofstock',
                'compare' => 'NOT LIKE',
            ) );
        }
        return $query_args;
    }, 10, 3);
    

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

    Tested on WooCommerce 3+ and works.