Site logo

Archived topic

Display element if custom post published

3 replies · Started by akal on June 1, 2022

Viewing posts 1–4 of 4

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
akal

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
akal

Awesome - glad to be of help!

This archived topic is closed to new replies.