0

Let's say I have a banner image I want to act as a background cover. Users manually upload their image with the Media library, which then associates that image with the post (image is handled using ACF).

Is there a way to have WP inject that image into a stylesheet? This doesn't seem possible given the WP loop only residing in the HTML template but I thought somebody might have an idea.

4
  • You can use WordPress Filesystem API to dynamically store contents in a file. Trigger that on saving the custom header. – Abhik Oct 7 '15 at 8:46
  • Abhik - curious if you can elaborate on this method with a full on answer below. Thanks. – serraosays Oct 7 '15 at 13:55
  • Nothing complected.. Just have a look here. codex.wordpress.org/Filesystem_API – Abhik Oct 7 '15 at 17:30
  • Thanks Abhik - just using the template method mentioned below seems to be the best solution with the least overhead. It's also server-side, so I dont have to worry about people not seeing the bg image render (another concern I've had debating different methods). – serraosays Oct 7 '15 at 19:48
2

Typically with themes that support custom styles/images, you define everything you can in your stylesheet, and then add the dynamic styles inline:

.header {
    background-position: 50% 50%;
    background-repeat: no-repeat:
    background-size: whatever;
}

And in your templates:

<div class="header"<?php if ( $image ) printf( ' style="background-image: url(%s);"', $image ) ?>>
   Title
</div>
4
  • This is what I was thinking about doing. I'll probably accept it as the right answer, just want to see if there are any other creative ways to go about this. – serraosays Oct 7 '15 at 13:55
  • The only other viable alternative I see is storing all your customisations in a generated file/linking to a script that serves a stylesheet, and quite frankly (unless you've got heaps of custom styles), is just not worth it. – TheDeadMedic Oct 7 '15 at 13:56
  • Again, similar to what I was thinking. You'd have to insert the image SRCs with JS - and that seemed uglier than inline style declarations being generated by the templating system. – serraosays Oct 7 '15 at 13:58
  • This really is a pretty easy method to implement and it's working great - thanks TheDeadMedic. – serraosays Oct 7 '15 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.