wordpress 高级自定义字段背景图片

5ku*_*kud 1 css php wordpress background-image custom-fields

我正在尝试设置通过自定义字段插件上传的图像,并将其显示为 div(在滑块中使用)的背景。

但是图像没有显示......我在自定义字段中有文本并且显示正常,所以我认为它与我用来拉入图像的代码行有关。

我正在尝试使用图像设置 .slide1 的背景。

自定义字段名称是 slide1_background。

HTML:

<div class="slide1" style="background-image:url('<?php the_field('slide_bg1'); ?>');">
<div class="slide1-cont"><p class="slide-text">
<h1><?php the_field('slide_title1'); ?></h1>
<img src="<?php bloginfo('template_directory')?>/images/line.png" /></p>
<p><?php the_field('slide_content1'); ?></p></div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

.slide1{
background-repeat:no-repeat;
background-size:cover;
background-position:center;
height: 800px;
}
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 5

看看您的问题中的代码与您将其设置为图像源的另一个答案中的评论中的代码相比,您尝试设置背景图像的不同之处。

the_field('slide_bg1') 返回一个数组,因此您尝试将背景图像源设置为 PHP 数组,该数组将转换为字符串“数组”,因此在您的 HTML 中它看起来像: background-image:url('Array')

需要先获取字段,然后回url显返回数组的元素作为背景图片的来源:

$image = get_field( 'slide_bg1' );
if ( !empty( $image ) ) { ?>
    <div class="slide1" style="background-image:url('<?php echo $image['url']; ?>');">
<?php }
Run Code Online (Sandbox Code Playgroud)