Archived topic
Dynamic conditioning of GeneratePress Elements
5 replies · Started by William on June 20, 2022
Hi there,
I love the introduction of dynamic content, headings etc., and love the use of Elements in GP - the possibilities for design are endless.
However, one area that I feel is a little limited is the conditioning of the Elements - for some Elements, I think it would be beneficial to have them dynamically appear/disappear depending on certain conditions. A company called Sunbreak does this. Is there something like this on the scope for GeneratePress? I love the user conditions you can apply. But, for example, I have category archive pages that now have the ability to filter the posts on them, see here.
I can currently apply the element that contains the filter to all category archive pages. However, I have a lot of category archive pages that have 1 post, or not many - in these occurrences, it would make sense to not show the filter, since the posts are so low in number the filter wouldn't be useful. With this, it would make sense to have a conditioning rule that if the category has over 'X' posts, to show the element - is this possible?
Kind regards,
Will
Hi Will,
you can use the generate_element_display filter for all these kinds of additional options:
https://docs.generatepress.com/article/generate_element_display/
What we need to add to that is a way to count how many posts are in the current term.
Bit of googling i found this:
$count = $GLOBALS['wp_query']->post_count;
So putting it together:
add_filter( 'generate_element_display', function( $display, $element_id ) {
$count = $GLOBALS['wp_query']->post_count;
if ( 100 === $element_id && $count > 1 ) {
$display = false;
}
return $display;
}, 10, 2 );
Change the 100 to the Element ID.
And adjust the $count > 1 condition to suit your needs.
Bigger picture, we are looking at how we can make the Display conditions of elements more flexible without the need for lots of code. Its definitely something we want to do.
Thanks for that David, that's amazing. The one thing is that I want the element to not display when $count is less, say, 2. When I put $count < 2 instead of $count > 1 it does not seem to work?
Oh my - what was i thinking there lol.
Try this:
if ( 100 === $element_id && 2 > $count ) {
Ah that's the trick - thanks for your awesome help David!!
Awesome - glad to be of help!