Support

Account

Home Forums General Issues Set custom background-image to div – if/else statement

Helping

Set custom background-image to div – if/else statement

  • Hi there,

    I’m just getting to grips with ACF – and it’s great! I do however have very little PHP knowledge, so I’m probably doing something very obviously wrong here.

    I have a banner on each page of my website that contains a title + text. Each page’s banner should have it’s own unique background-image applied.

    I’ve managed to get this working using the following code:

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

    That does pull in the image and display it as a background image, so great!

    What I want to know is how do I wrap this in an if/else so if the field isn’t populate in the CMS, so there’s no image specified. It doesn’t add the style declaration?

    I tried using this:

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

    But then the image didn’t display at all – any ideas?

    Thanks in advance! 🙂

Viewing 1 post (of 1 total)

The topic ‘Set custom background-image to div – if/else statement’ is closed to new replies.