Get the ID of a separate blog page with using a static front page

Snippets / Wordpress

Whilst developing a site for a client, I wanted to set up a page that displayed all blog post but was separate from the home page. This is very easy to do when setting up a WordPress website, you simply create your  “home page” and  “blog page”,  then  you go to settings > reading. In here You can set the home page as the front page of your website and the blog page as the blog archive.

However, in my situation, I wanted to show a header image specifically set as the featured image of the blog archive page. My initial thought was to run the loop as I had done on all the other pages , then use the rewind_post() function to use the same loop again to call other fields.

However on a blog page, this calls the fields from  first blog post that has been archived. The solution was to use the ID of the page to retrieve the featured image url. When using a static front page and a different blog page , the WordPress function to get the ID is :

 

get_option( 'page_for_posts' )

So to put it into context, I wanted to pull in the featured image i’d uploaded for the page ‘blog’, this is the code I used

if( have_posts() ) : while ( have_posts() ): the_post();
$postid = get_option( 'page_for_posts' );
if(is_home()){ $thumb_id = get_post_thumbnail_id($postid);
}else{$thumb_id = get_post_thumbnail_id();
}
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'full', true);
$thumb_url = $thumb_url_array[0];
endwhile;endif;
rewind_posts();