How to add HTML in "No products were found matching your selection" WooCommerce message

Viewed 276

In WooCommerce, The "No products were found matching your selection." text appears when no products are found in the loop.

However, I want to add HTML in the text, so I use the gettext filter hook. Via str_ireplace I can easily overwrite the text:

function change_empty_category_text($translated) {
   $translated = str_ireplace ('No products were found matching your selection.', 'sorry! we are not delivering products from this category to you pin code at the moment.', $translated);
   return $translated;
 }
add_filter( 'gettext', 'change_empty_category_text' );

However, when I want to add HTML in this text:

function change_empty_category_text($translated) {
   $translated = str_ireplace ('No products were found matching your selection.', 'sorry! we are not delivering products from this category to you pin code at the moment.\r\nplease visit the following categories instead\r\n<a href = 'www.example.com/category1'>category 1</a>\r\n<a href = 'www.example.com/category2'>category 2</a>\r\n<a href = 'www.example.com/category3'>category 3</a>', $translated);
   return $translated;
 }
add_filter( 'gettext', 'change_empty_category_text' );

It has no result. Instead, I am getting the same exact text as written in the replacement.

Any advice?

1 Answers

The text you want to adjust can be found in templates/loop/no-products-found.php, so you could overwrite the template file versus using the gettext filter hook, since this hook is executed multiple times on every page load.

However, there is another option. Since wc_no_products_found uses function_exits, see: /includes/wc-template-functions.php on line 3254-3262 @version 2.5.0

if ( ! function_exists( 'wc_no_products_found' ) ) {

    /**
     * Handles the loop when no products were found/no product exist.
     */
    function wc_no_products_found() {
        wc_get_template( 'loop/no-products-found.php' );
    }
}

More info: What's "function_exists" in Wordpress


So instead of using the existing template file, which is called via wc_get_template() in the function, we are going to rewrite the function with our own function.

So you get:

function wc_no_products_found() {
    echo '<p class="woocommerce-info" style="display:block;">' . 
        __( 'Sorry! we are not delivering products from this category to you pin code at the moment.<br>Please visit the following categories instead', 'woocommerce' ) 
        . '<br><a href ="www.example.com/category2">category 2</a><br><a href="www.example.com/category3">category 3</a></p>';
}

As you can see the output is fully customizable to your needs. CSS adjustments may be required, since this is theme dependent.

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

Related