Search code examples
phpwordpressadvanced-custom-fields

How to use ACF to make a background image


Hi There I am trying to make a background image be choose able via an ACF rule in my block editor via WordPress. I cannot get this to work for the life of me I must be missing something stupid any help will help here is what I have at the moment.

<div style="background-image: url(<?php echo get_field('my_background'));"></div>

In this code assume my_background is our ACF field my ACF field is set up as a Image block set to URL but I cant make any leeway with this any help will be appreciated.

As menctioned this is being used in this block here

    <div style="<div id="mainPhoto" style="background-image: url(<?php the_field('$roomFacilitysBackgroundImage'); ?>);">">
                <h5>Room Facilities</h5>
                <div class="facilities facilities-column-50">
<?php
                    if  ($roomFacilitiesList3) {

                        foreach ($roomFacilitiesList3 as $roomFacilitiesList3 ) {
                            echo '<div>'.$roomFacilitiesList3.'</div>' ;
                        }
                    }
?>
                </div>
            </div>

This holds a outdated piece of background image to the one Above in the question


Solution

  • you write

    <div style="background-image : url(<?php the_field('$youVarName'); ?>)> "

    try with :

    $yourImageUrl = get_field('nameOfTheField);
    style ='background-image:' url(<?= $yourImageUrl ?>)
    

    if it's still don't work try to dump $yourImageUrlif it's not defined there is 2 option :

    1. you write the wrong field name

    2. you'r not in the right context then try get_field('nameOfTheField','Post_Or_PostID')where Post_Or_PostIDis where the field come from (post, option page ,....)

    3. option it's good in php but you'r div is to small to display the background