dimanche 5 août 2018

Unique background-image per page with Advanced Custom Fields (ACF)

I have a banner area on each page of my site which contains a title and short description. Each banner can have a different background-image. So I'd like to control this in the Wordpress CMS so a client can upload an image of their choice for each page using ACF.

I do this with the following bit of code on the div that needs the image applied to it:

<div class="masthead" style="background: url('<?php the_field('masthead_image'); ?>') center center; background-size: cover;">

The thing that's not great about that is it's still adding the style tag even if there isn't an image uploaded. I think it'd be better if it only added the style="" if there's an image to display.

I tried to do that with the following code but it broke and no image was displayed:

<div class="masthead" <?php if( get_field('masthead_image') ): ?> style="background: url("<?php the_field('masthead_image'); ?>") center center; background-size: cover;"<?php endif; ?> >

Any ideas?

<div class="masthead" style="background: url('<?php the_field('masthead_image'); ?>') center center; background-size: cover;">
    <div class="wrap wrap--narrow align-center">
        <div class="hgroup">
            <h1 class="hgroup__title"><?php the_title(); ?></h1>
            <?php the_excerpt(); ?>
        </div>
    </div>
</div>

Aucun commentaire:

Enregistrer un commentaire