If your site contains a related posts widget or other Elementor posts widgets there may be times where that area is empty because the query returned zero results. In this article I will explain how to display a custom message when the Elementor posts query returns zero results.
Create a custom empty posts query function
This code will replace empty search queries with your own custom message. Replace PLACE YOUR MESSAGE HERE on line 4 with any message you like. You can use an Elementor template shortcode if you would like to add more complex content to this section.
add_action('elementor/query/query_results', function($query) {
$total = $query->found_posts;
if ($total == 0) {
echo 'PLACE YOUR MESSAGE HERE';
}
});
Add the empty posts query function to your website
After modifying the above code add the custom query to your child theme functions.php file or as a snippet using a plugin. You should now see your custom message when Elementor post queries are empty.
Add a customized message for specific post types
You may want to display different custom messages for different post types. For example an empty related events query could default to a message saying ‘there are no related events’ or if you want to get more advanced you could build an Elementor template that contains the fallback events list and then include that shortcode in your function.
In the example below I added custom messages for event, course and quiz post types. Modify this code as needed to add custom messages for your desired post types.
add_action('elementor/query/query_results', function($query) {
$total = $query->found_posts;
if ($total == 0) {
if ( $query->get("post_type") == "event" ) {
echo "CUSTOMIZED MESSAGE FOR THE EVENT POST TYPE";
}
if ( $query->get("post_type") == "course" ) {
echo "CUSTOMIZED MESSAGE FOR THE COURSE POST TYPE";
}
if ( $query->get("post_type") == "quiz" ) {
echo "CUSTOMIZED MESSAGE FOR THE QUIZ TYPE";
}
}
});