Site logo

Archived topic

How to check in php if featured image is disabled?

5 replies · Started by Marc on June 21, 2022

Viewing posts 1–6 of 6

Good day, I am using this code to display the featured image in fullwidth:

<?php if ( is_single() ) : 
           if ( has_post_thumbnail() ) { ?>
               <div class="featured-image-in-header">
                   <?php the_post_thumbnail(); ?>
               </div>
           <?php }
endif; ?>

That works perfectly. Now I have some posts where I have a featured image stored, but I don't want to show it in the post. For this I use the function "Disable Elements" -> "Featured Image".

How do I need to extend the script to take into account whether the display of the featured image is enabled or disabled?

Thanks a lot for a tip!

zan

Hi Ying, thanks for the super fast reply and for the tip! I just tried around a bit, but unfortunately I can't get it to work the way I want it to.

Basically it does work, but it's too cumbersome for editors to use the location settings to set whether the image is displayed on a specific post or not. It would be much easier if they could simply specify on each post whether the featured image should be displayed or not, and if it is enabled, it should then be output in fullwidth.

I guess I just need to add just another IF condition to my PHP to check if the featured image is enabled or disabled for the post. But unfortunately I don't know the name of this condition...

bye, Marc

Hi Marc,

In-line with your code, you can try something like:

<?php if ( is_single() ) : 
$is_featured_disabled = get_post_meta(get_the_ID(), '_generate-disable-post-image');
           if ( has_post_thumbnail() && ! $is_featured_disabled[0] ) { ?>
               <div class="featured-image-in-header">
                   <?php the_post_thumbnail(); ?>
               </div>
           <?php }
endif; ?>

However, if you opt to use a Block Element, you can use this code as well:

add_filter( 'generate_block_element_display', function( $display, $element_id ) {
	$is_featured_disabled = get_post_meta(get_the_ID(), '_generate-disable-post-image');
    if ( 395805 === $element_id && has_post_thumbnail() && ! $is_featured_disabled[0] ) {
        $display = true;
		
    } else {
		$display = false;
	}
    return $display;
}, 15, 2 );

This code will allow the Block Element to display if the featured image is enabled.

Adding PHP reference: https://docs.generatepress.com/article/adding-php/#code-snippets

Kindly replace 395805 with your Block Element’s ID.

Hope this helps!

Hi Fernando,

the first script does exactly what I wanted to achieve, thank you very much for the great support and best regards!

spirou

You’re welcome Marc! Glad that worked!

This archived topic is closed to new replies.