我正在尝试创建一个代码,如果有特色图片,它将显示一张照片,否则它将只显示页面标题。此代码位于我的标题中,因为它靠近徽标。
当我在没有特色图片的页面上使用此代码时:
<?php
if ( get_post_thumbnail_id() ==\'\' ) {
echo \'no picture\';
echo \'its id is \'.get_post_thumbnail_id();
}
else {
echo \'there is a thumbnail\';
echo \'its id is \'.get_post_thumbnail_id();
}
?>
它返回“有一个缩略图,它的id是-3。”
当我在没有特色图片的页面上运行此代码时:
<?php if ( has_post_thumbnail() ) :?>
<img class="img-responsive logo-main scale-with-grid" src="<?php the_post_thumbnail_url(\'full\'); ?>"/>
<div class=\'text-box\'>
<p class=\'dataNumber title\'><?php the_title();?> </p>
</div>
</div>
<?php else: ?>
<div class="logo-main scale-with-grid">no postthumb</div>
<div class=\'text-box\'>
<p class=\'dataNumber title\'><?php the_title();?> </p>
</div>
</div>
<?php endif; ?>
它返回以下内容:
<div class="containerBox">
<img class="img-responsive logo-main scale-with-grid" src="">
<div class="text-box">
<p class="dataNumber title">Careers </p>
</div>
</div>
如果我设置了一个特征图像,两个代码都可以正常运行。
根据Jack的说法,我尝试了同样的结果:
if ( has_post_thumbnail(get_the_id()) ) {
echo \'there is a thumbnail for post \'.get_the_id().\' its id is \'.get_post_thumbnail_id();
}
else {
echo \'no picture for post \'.get_the_id();
}
但它确实显示了正确的页面id。
最合适的回答,由SO网友:Johansson 整理而成
请尝试以下代码:
<?php
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,\'full\', true);
if ( !empty($thumb_url[0])) {
echo "There is a thumbnail and it\'s id is: ".$thumb_id;
} else {
echo \'There is no picture.\';
}
?>
对于第二个代码,请使用:
<?php
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,\'full\', true);
if ( !empty($thumb_url[0]) ) : ?>
<img class="img-responsive logo-main scale-with-grid" src="<?php echo $thumb_url[0]; ?>"/>
<div class=\'text-box\'>
<p class=\'dataNumber title\'><?php the_title();?> </p>
</div>
</div>
<?php else: ?>
<div class="logo-main scale-with-grid">no postthumb</div>
<div class=\'text-box\'>
<p class=\'dataNumber title\'><?php the_title();?> </p>
</div>
</div>
<?php endif; ?>