Php Wordpress使用默认图像作为背景

Php Wordpress使用默认图像作为背景,php,wordpress,image,loops,Php,Wordpress,Image,Loops,我有一些代码,使用一个帖子的特色图像作为一个DIV的背景 <?php if (has_post_thumbnail( $post->ID ) ): $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); endif; ?> <div class="news-image" style="background-image:

我有一些代码,使用一个帖子的特色图像作为一个DIV的背景

 <?php if (has_post_thumbnail( $post->ID ) ):
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); 
endif; ?>
<div class="news-image" style="background-image: url(<?php echo $image[0]; ?>); background-repeat: no-repeat;  background-color: #000; background-position: center center; background-size: cover;">


当然你能做到,我做了一些粗略的片段,希望你能从我的评论中得到信息:)



显示特征图像,但不显示默认图像。你能给你的代码添加一个真实世界的链接来告诉我默认图像的位置吗?如果图像是如何适合您的代码?我在第一行的
add_option
中有硬编码的url。。希望这能帮助你,不幸的是,对于没有特色图片集的帖子,仍然没有显示默认图片。代码在URL字段中没有这样的内容:style=“background image:URL();:URL参数为空。只是想签入并查看您是否对URL参数返回空的原因有任何想法?hi@lowercase我编辑了此文件并测试了这段代码,它的工作原理与我预期的一样..不知道为什么会得到空字符串..我觉得不太对劲。。
<?php 

// first you have to define and save your default image somewhere,, save it in options table for ex.. like this:

add_option( 'my_default_pic', 'http://www.website.com/image/jpg', '', 'yes' );


// then on page or template use like this
if (has_post_thumbnail( $post->ID ) ){
    $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' )[0]; 
} else {
    $image = get_option( 'my_default_pic' );
}
?>

<div class="news-image" style="#000 no-repeat center center background: url(<?php echo $image; ?>);"> 
    body = lorem ipsum
</div>