我创建了一个if语句来检查当前的wordpress页面/帖子是否有特征图像集。如果不是,我希望脚本回显占位符图像的URI。脚本运行时没有任何PHP错误,但是当没有可用的功能映像时,它会回显以下background: url(h)
而不是占位符的URI。我可以看到问题出在内联回显$image[0]
但是我不知道如何解决这个问题。
<?php if(is_home()) {
$image = wp_get_attachment_image_src(get_post_thumbnail_id(get_option('page_for_posts')),'full');
} elseif (has_post_thumbnail($post->ID)) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail, page_for_posts' );
} else {
$image = get_template_directory_uri() . '/assets/images/placeholder.png';
}
?>
<div class="hero-inner" style="background: url(<?php echo $image[0]; ?>) no-repeat center center; background-size: cover;">
[...]
</div>
答案 0 :(得分:1)
if(is_home()) {
$image = wp_get_attachment_image_src(get_post_thumbnail_id(get_option('page_for_posts')),'full');
} elseif (has_post_thumbnail($post->ID)) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail, page_for_posts' );
}
if($image){
$image = $image[0];
}
else {
$image = get_template_directory_uri() . '/assets/images/placeholder.png';
}
?>
<div class="hero-inner" style="background: url(<?php echo $image; ?>) no-repeat center center; background-size: cover;">
[...]
</div>
答案 1 :(得分:0)
将var $ image更改为$ image [0]以获取最后的其他内容。
<?php if(is_home()) {
$image = wp_get_attachment_image_src(get_post_thumbnail_id(get_option('page_for_posts')),'full');
} elseif (has_post_thumbnail($post->ID)) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail, page_for_posts' );
} else {
$image[0] = get_template_directory_uri() . '/assets/images/placeholder.png';
}
?>
<div class="hero-inner" style="background: url(<?php echo $image[0]; ?>) no-repeat center center; background-size: cover;">
[...]
</div>