Back to Community

How to Conditionally Hide the Query Total Block When No Results Are Found

21 threads Sep 16, 2025 CoreFixing wordpress

Content

A common challenge when using the Query Loop block is managing the Query Total block, which displays the number of posts found. While useful, it can be visually jarring when a query returns zero results, as it displays "0 results found." Many users want this block to hide automatically in such cases, but the block itself lacks a built-in setting for this behavior.

Why This Happens

The Query Total block is a simple counter. It does not have conditional logic to evaluate whether posts were actually found in the associated Query Loop. Furthermore, it does not output any specific CSS class based on the post count, which makes it impossible to hide using CSS alone.

How to Fix It: A JavaScript Workaround

Since a native WordPress solution isn't currently available, the most effective method is to use a small JavaScript snippet. This script will detect when the Query Loop is empty and then dynamically hide the Query Total block.

Step-by-Step Instructions

  1. Add a Custom Class: First, you need to uniquely identify your Query Total block. Edit the block and add a custom HTML class to its Advanced settings panel. For example, you could use custom-query-total.
  2. Add the JavaScript Code: Insert the following code snippet into your site. You can do this by adding a Custom HTML block to your template (if your theme allows it) or by using a plugin like "Custom Code Snippets."
<script>
(function() {
    // Check if the main Query Loop container has no posts
    const queryLoopContainer = document.querySelector('.wp-block-query');
    if (queryLoopContainer && !queryLoopContainer.querySelector('.wp-block-post')) {
        // Find your specific Query Total block and hide it
        const totalBlock = document.querySelector('.custom-query-total');
        if (totalBlock) {
            totalBlock.style.display = 'none';
        }
    }
})();
</script>

How it works: This script runs when the page loads. It looks for the main Query Loop block. If it finds the loop but finds no individual post blocks inside it, it then searches for your specific Query Total block (using the custom class you added) and sets its display property to 'none', effectively hiding it from view.

Important Considerations

  • Theme and Plugin Conflicts: As with any custom code, there is a potential for conflict with your theme or other plugins. It's always a good practice to test this on a staging site first.
  • Future Updates: This is a workaround. A future update to the WordPress block editor might introduce a native option for this, which would make this custom code unnecessary.

This approach provides a clean, user-experience-focused solution to a common design problem with the Query Loop block.

Related Support Threads Support