I’m providing a theme setting to define a group of images for the frontpage background. On page load, I want to pick an image at random from this pool.
My approach is to add a line of inline CSS styling the html element with the given image url like this:
<style>
html {
background: url(images/random_image_3.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
</style>
Is there a preferred way of doing this ? Should i use a localize_style function I haven’t found out about, or just echo the css out using the right hook?
And what’s the best hook for this, only targeting the front facing site?
You could use the
wp_head
hook and inject your <style> tag directly into the <head>. Note: make sure you’re firing thewp_head()
function in your template (which you should be doing already).Edit
Another option is to dynamically generate the stylesheet, and randomly choose
$image
in that file. Then you’d inject your stylesheet <link …> viawp_enqueue_scripts
hook (yes, wp_enqueue_scripts), and enqueue withwp_enqueue_style
.