Blog about tips & tricks for CMS enhancement

eric.petersson

WordPress - Set image styled inline with custom fields


If you're just like me and are using Advanced Custom Fields in your WordPress solutions then you might have asked yourself how to set an image from one of your field as an inline style in the html markup? Well, here is one solution:

<?php
    // get the image from the advanced custom fields plugin
    $mainImage = get_field("standard_page_main_image");
?>

<section id="main-image-section" style="background-image: url('<?php echo $mainImage['url']; ?>')">
    //
    /* ... neccessary code goes here */
    //
</section>

Head into the backoffice of WordPress and add the main image as an custom field like the image below:

inline styled custom field image for wordpress

In my case, I would like the image to take up the fullscreen section of the webpage I am creating. Therefor, I am adding CSS like the following:

.main-image-section {
    margin: 0;
    width: 100vw;
    height: 100vh;

    background-repeat: no-repeat;
    background-position: center center;

    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Result

You should now have an inlined styled image for WordPress!
result of inline styled custom field image wordpress

That's it for today!
Good day, sir/ms/mrs!