Support » Fixing WordPress » If Featured Image Exists Use As Header Image

  • Hello,
    I am using a child version of the Sydney theme, what I am trying to do is swap out the header image with the featured image of a page/post/custom post if it exists, I thought it would be something like this
    src="<?php if(has_post_thumbnail($post_id)){the_post_thumbnail();} else {header_image();} ?>"
    But so far cannot get this to work, has anyone done similar?

    Thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • Is this line of code inside your loop? if so maybe you don’t need ‘$post_id’. and also, I don’t think ‘$post_id’ is a core global variable…I could be wrong though. So if your code is outside the loop maybe try ‘$post->ID’ instead?

    I tried removing $post_id and also replacing with $post->ID but neither does the trick unfortunately. I have the code in header.php like so:

    	<?php do_action('sydney_after_header'); ?>
    
    	<div class="sydney-hero-area">
    		<?php sydney_slider_template(); ?>
    		<div class="header-image">
    			<?php sydney_header_overlay(); ?>     
    
        <img class="header-inner" src="<?php if(has_post_thumbnail($post->ID)){the_post_thumbnail();} else {header_image();} ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" alt="<?php bloginfo('name'); ?>" title="<?php bloginfo('name'); ?>">
    			
    		</div>
    		<?php sydney_header_video(); ?>

    So this is in your header file? I take it that it comes BEFORE your loop then. Try passing the ‘$post->ID’ variable into a different function ‘get_the_post_thumbnail()’ like this:

    <?php do_action('sydney_after_header'); ?>
    
    	<div class="sydney-hero-area">
    		<?php sydney_slider_template(); ?>
    		<div class="header-image">
    			<?php sydney_header_overlay(); ?>     
    
        		<img class="header-inner" src="<?php if( has_post_thumbnail($post->ID) ) { echo get_the_post_thumbnail($post->ID); } else { header_image(); } ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" alt="<?php bloginfo('name'); ?>" title="<?php bloginfo('name'); ?>">
    			
    		</div>
    		<?php sydney_header_video(); ?>

    and see if that does anything. You should also inspect your code in your browser to see what gets output each time. it helps troubleshoot things like this.

    • This reply was modified 1 year, 10 months ago by Mr Case.
    • This reply was modified 1 year, 10 months ago by bcworkz. Reason: code fixed

    Hi, sorry for the delayed response I have been out of the office so not been working on the project. This has worked a treat! Thanks 🙂

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘If Featured Image Exists Use As Header Image’ is closed to new replies.