Archived topic
Hide block element with query loop if there are no results
10 replies · Started by Abigail on April 5, 2023
Hi,
I have created a block element with a query loop with a tag filter to show related posts. Not every post has other related posts, so only the header of that block is displayed.
How can I hide the block if there are no results?
Hi Abigail,
Can you provide a link to a page where there are related posts and a page where there aren't?
You may use the Private Information field for this: https://docs.generatepress.com/article/using-the-premium-support-forum/#private-information
Hi Fernando,
I have added the links to the private information field.
Can you place the Headline Block and the Query Loop Block inside a Container Block? Then place the Headline Block after the Query Loop Block.
We'll fix the positioning and hide the title when there are no posts through custom code.
Like this? https://gyazo.com/7962d5cec220c59f96cccaa2eb37b6b3
I can still see the header.
Hi there,
what is the related condition? Is it posts with the same tag as the current post ?
And i assume that post is the only one with that tag ?
Hi,
I don't quite understand your questions and I wonder if it is relevant. There is nothing wrong with the query loop, it works as expected.
I wonder what the possibilities are to hide a block if there are no results. This situation will only occur if a category/tag is new and has no related posts yet.
For example, can I solve this via configuration of the blocks or do I need custom code?
Like this: https://share.getcloudapp.com/o0uYR6XJ
The Headline is under the Query Loop within a Container Block.
Then, add this CSS through Appearance > Customize > Additional CSS:
.gb-grid-wrapper.gb-grid-wrapper-f6030caa.gb-query-loop-wrapper:is(:empty) + .gb-headline {
display: none;
}
.gb-container.gb-container-2aa41bb5 {
display: flex;
flex-direction: column;
}
.gb-container.gb-container-2aa41bb5 .gb-grid-wrapper-f6030caa{
order: 1;
}
Thanks that works! What is the reason to put the header under the query loop?
In Fernandos CSS, in the first rule, you will see the + between the two selectors.
The + is the next sibling combinator.
Which allows you to style an element that comes immediately after another element.
So what it does in this case is: if the "query loop is empty" + "make the headline" = display none.
It won't work the other way around.
My question was related, perhaps badly put across.
Currently the query is only run inside the query loop.
So checking if it has results outside the loop is not ( currently ) possible.
If the query was simply replicated then we could write a function to remove a block conditionally.
Such as count posts with matching tag or category terms.
Thanks Fernando and David!