0
votes

I'm building a wordpress theme and at the top of each page i'm displaying that pages featured image. I'm doing a quick query to check if it has a featured image using has_featured_image() however, when it comes to my blog page (home.php) - this query looks for the featured image of the first POST, not for the featured image of the PAGE.

How can I check to see if my blog PAGE has a featured image as the above code doesn't work.

3

3 Answers

0
votes

Figured this one out, the below piece of code will find out if your blog PAGE has a featured image rather than taking the featured image of the first POST.

$page_for_posts = get_option( 'page_for_posts' ); 
if (has_post_thumbnail( $page_for_posts )) {
    // do something
};
0
votes

Sam, do you have your full code for this? I am trying to display a pages featured image as a background image on a div and have it working on all pages except the blog page, where it displays the featured images for the latest blog post.

Thanks.

0
votes

I encountered the exact same issue. I have a site that uses featured images as hero graphics. I wanted the blog page to follow suit, but when I turned the static page into the custom blog posts index, my code no longer worked. I finally found a solution which I wrote into my conditional statements in header.php outside of the loop.

The first statement gets the featured image for a page:

<?php if ( has_post_thumbnail( $post_id )) { ?> 
<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID, 'thumbnail') ); ?>
<div class="grid_navigation" style="background-image: url('<?php echo $url ?>');">

The second checks if this is a home or blog page and grabs the URL for the static page turned blog index. I'm still figuring this out, but once a page is set to "blog" it gets thrown out of the bank of 'regular' pages. Hah, not sure that makes sense. So requesting a post ID isn't so simple anymore...

<?php } elseif (is_home() && get_option('page_for_posts') ) { ?> // Gets featured image of page set to home or blog
<?php $url = wp_get_attachment_url(get_post_thumbnail_id(get_option('page_for_posts')),'full'); ?>
<div class="grid_navigation" style="background-image: url('<?php echo $url ?>');">

And then the last statement to close it all:

<?php } else { ?>
<div class="grid_navigation">
<?php } ?> 

Here is the full conditional statement all together:

<?php if ( has_post_thumbnail( $post_id )) { ?> 
<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID, 'thumbnail') ); ?>
 <div class="grid_navigation" style="background-image: url('<?php echo $url ?>');">

<?php } elseif (is_home() && get_option('page_for_posts') ) { ?> // Gets featured image of page set to home or blog
<?php $url = wp_get_attachment_url(get_post_thumbnail_id(get_option('page_for_posts')),'full'); ?>
<div class="grid_navigation" style="background-image: url('<?php echo $url ?>');">

<?php } else { ?>
<div class="grid_navigation">
<?php } ?>