最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to get the Page featured image, not the Post featured image

programmeradmin1浏览0评论

I currently have in my header.php:

<?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'header-large' ); ?>

<?php if ( has_post_thumbnail() ) { ?>
<div id="wrapper-navbar" itemscope itemtype="" style="background-image: url('<?php echo $backgroundImg[0]; ?>');">
<?php } else { ?>
<div id="wrapper-navbar" itemscope itemtype="">
<?php } ?>

Which sets the background image if there is a featured image on the pages and posts. If there is none then there is a fall back where I have a default background image.

My problem arises on the Blog page - The page which is set as the "Posts Page'

The background image displayed on the "Posts Page" is the featured image of the latest Post on the list, NOT the featured image I have set for the page.

How do I display the featured image of the Page and not of the latest post on the list?

I currently have in my header.php:

<?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'header-large' ); ?>

<?php if ( has_post_thumbnail() ) { ?>
<div id="wrapper-navbar" itemscope itemtype="http://schema/WebSite" style="background-image: url('<?php echo $backgroundImg[0]; ?>');">
<?php } else { ?>
<div id="wrapper-navbar" itemscope itemtype="http://schema/WebSite">
<?php } ?>

Which sets the background image if there is a featured image on the pages and posts. If there is none then there is a fall back where I have a default background image.

My problem arises on the Blog page - The page which is set as the "Posts Page'

The background image displayed on the "Posts Page" is the featured image of the latest Post on the list, NOT the featured image I have set for the page.

How do I display the featured image of the Page and not of the latest post on the list?

Share Improve this question asked Jul 25, 2019 at 5:17 iamonstageiamonstage 1671 silver badge9 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You might be able to do this by calling wp_reset_postdata(); otherwise you will need to get the blog page ID and set that on the line before instead:

if ( is_home() ) {$post_id = get_option( 'page_for_posts' );} else {$post_id = $post->ID;}
$backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'header-large' ); ?>

Note the is_home() is actually used for the blog page, as distinct from is_front_page() which is actually for the "homepage".

发布评论

评论列表(0)

  1. 暂无评论