Using WordPress ‘loop_no_results’ PHP action

The loop_no_results WordPress action is triggered when no results are found in a post query.

Usage

add_action('loop_no_results', 'my_custom_function');
function my_custom_function($query) {
    // your custom code here
}

Parameters

  • $query (WP_Query): The WP_Query instance.

More information

See WordPress Developer Resources: loop_no_results

Examples

Display a custom message when no posts are found

This example will display a custom message when there are no posts found in the query.

add_action('loop_no_results', 'display_no_posts_message');
function display_no_posts_message($query) {
    echo '**Sorry, we could not find any posts.**';
}

Redirect to a custom page when no posts are found

This example will redirect the user to a custom page when there are no posts found in the query.

add_action('loop_no_results', 'redirect_to_custom_page');
function redirect_to_custom_page($query) {
    wp_redirect(home_url('/custom-page/'));
    exit;
}

Load a custom template for no results

This example will load a custom template when there are no posts found in the query.

add_action('loop_no_results', 'load_no_results_template');
function load_no_results_template($query) {
    get_template_part('template-parts/content', 'no-results');
}

Add a custom CSS class to the body when no posts are found

This example will add a custom CSS class to the body element when there are no posts found in the query.

add_action('loop_no_results', 'add_custom_body_class');
function add_custom_body_class($query) {
    add_filter('body_class', function($classes) {
        $classes[] = 'no-results';
        return $classes;
    });
}

Log when no results are found

This example will log a message when there are no posts found in the query.

add_action('loop_no_results', 'log_no_results');
function log_no_results($query) {
    error_log('No results found for the query.');
}