- This topic has 3 replies, 2 voices, and was last updated 3 years, 10 months ago by
David.
-
AuthorPosts
-
June 1, 2022 at 1:31 am #2239971
akal
Hi,
I’m already using this code to display elements depending certain conditions :add_filter( 'generate_element_display', function( $display, $element_id) { global $post; //2415 = Header SubCampings Template (H1 / featured img / ACF text area) if ( 2415 === $element_id && get_field('body_classname') !== "subcp" ) { $display = false; } //4200 = Header SubHome Template (H1 / Excerpt / featured img ) else if ( 4200 === $element_id && get_field('body_classname') !== "subhome" ) { $display = false; } else if (etc...) return $display; }, 10, 2 );Now I have a new challenge : I would like to build a page that will display – or not – a whole section (Block – Hook element) depending if at least one of my custom post “mh_accs_post_type” is published. Inside this section, I will display a loop of my custom post(s), so if one or many custom post are published, this section element should appear in my page and display the loop, but if there is no published custom post, there is no loop to display so no reason to display the element inside the page (I hope I’m clear enought…)
So I’ve tryed to adapt the above code with this one from here :
add_filter( 'generate_element_display', function( $display, $element_id) { global $post; $args = array( 'post_type' => 'mh_accs_post_type', ); $loop = new WP_Query( $args ); //2415 = Header SubCampings Template (H1 / featured img / ACF text area) if ( 2415 === $element_id && get_field('body_classname') !== "subcp" ) { $display = false; } //4224 = Middle Content Residential Template (background / cpt loop slider / Some text ) else if ( 4224 === $element_id && $loop->have_posts() ) { $display = true; } return $display; }, 10, 2 );But that doesn’t work, so I guess it’s more complicated … Do you think it is doable ? any clues ?
Best regards
akalJune 1, 2022 at 4:35 am #2240122David
StaffCustomer SupportHi there,
you could try the
wp_count_postsfunction instead of creating a new query:https://developer.wordpress.org/reference/functions/wp_count_posts/
The condition would be something like this:
if( wp_count_posts( 'mh_accs_post_type' )->publish > 1 ) { // do something if post type has published posts }June 2, 2022 at 8:14 am #2241580akal
Hi David,
many thanks for the wp_count_posts function suggestion !else if( 4224 === $element_id && get_field('page_classname') === "residentiel" ) { if( wp_count_posts('mh_accs_post_type')->publish >= 1 ) : $display = true; else: $display = false; endif; } return $display;That did the trick ^^
Best regards
akalJune 2, 2022 at 12:22 pm #2241757David
StaffCustomer SupportAwesome – glad to be of help!
-
AuthorPosts
- You must be logged in to reply to this topic.