-2

I have been looking around for a way to essentially allow a user to upload images in the WordPress backend and for the images to be used on the front-end as background-image for a div, therefore allowing support for the following CSS

background: url('');
background-repeat: no-repeat;
background-size: cover;

I found a question which had an answer which I liked, but i'm not great with PHP and wouldn't know how to implement it with 'Toolset Types' so that it adds the background url to the stylesheet and overrides it when the client wants to add a new image. How to upload image file from computer and set as div background image using jQuery?

I could also put the images on the page itself, and allow users to do it that way, but I need to use the background properties so that the image covers the div. If anyone knows any styles that can do this without the background styling, that would be great.

CalGregoryy
  • 13
  • 1
  • 6

2 Answers2

1

I would suggest you take a look at Advanced Custom Fields. You can add the functionality to upload an image to a post, page, custom post type, term and so on.

When the image is uploaded, you can retrieve the url. If it's uploaded to a post, you can get it like this.

<?php
  $image_url = get_field('image', $post_id);
?>

And set the background image url to div.

<div class="bg__full" style="background-image: url('<?php echo $image_url ?>')></div>

You can then style the div with other properties inline or with css like.

.bg__full {
  background-repeat: no-repeat;
  background-size: cover;
}
Gregor Ojstersek
  • 1,369
  • 7
  • 12
0

//WordPress

Requirements -

After installing both of the plugins, navigate to "Custom Fields" in your WordPress backend and create your custom image fields (Make sure to save your fields). Custom Image Field Picture

Then navigate over to XYZ PHP Code, and create a code snippet with the following code -

<?php
$image_url = get_field('Your_Custom_Field');
?>
<div class="Your_Image_Class" style="background-image: url('<?php echo $image_url ?>')"></div>

Make sure you change 'Your_Custom_Field'to your own, along with class="Your_Image_Class".

From here, you can save and navigate back to the main page of "XYZ PHP Code" and grab the shortcode it provides. Image Of Shortcodes

Place the shortcode in the page you want to display the image, then scroll to the bottom of that page and add your images. If all went well, your image should start displaying as the background of such div.

Thanks to Gregor Ojstersek for his help

CalGregoryy
  • 13
  • 1
  • 6