Search code examples
phpwordpresswoocommerceproductshortcode

Display a message if there are no products returned for a WooCommerce shortcode


I have a page using the shortcode [products columns="4" category="free-prize-draws"] to show products in a specific category. If there are no products in that category, the page is blank.

Is it possible to have the page display a message if there are no products returned for a product shortcode? In the same way that a message is displayed if there are no search results for a particular search query.


Solution

  • You can use the do_action( "woocommerce_shortcode_{$this->type}_loop_no_results", $this->attributes ); action hook.

    So you get:

    function action_woocommerce_shortcode_products_loop_no_results( $attributes ) {
        echo __( 'My custom message', 'woocommerce' );
    }
    add_action( 'woocommerce_shortcode_products_loop_no_results', 'action_woocommerce_shortcode_products_loop_no_results', 10, 1 );