localize inline css

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:

Read More
<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?

Related posts

Leave a Reply

1 comment

  1. You could use the wp_head hook and inject your <style> tag directly into the <head>. Note: make sure you’re firing the wp_head() function in your template (which you should be doing already).

    add_action('wp_head', 'random_background_image_wpse_83275');
    function random_background_image_wpse_83275() {
        $images = array(
            '/path/to/image1.jpg',
            '/path/to/image2.jpg',
            '/path/to/image3.jpg',
            '/path/to/image4.jpg',
        );
    
        $image = $images[rand(0, count($images)-1)];
    
        echo '
            <style>
                html { 
                    background: url("' . $image . '") no-repeat center center fixed; 
                    -webkit-background-size: cover;
                    -moz-background-size: cover;
                    -o-background-size: cover;
                    background-size: cover;
                }
            </style>';        
    } // END function random_background_image_wpse_83275
    


    Edit

    Another option is to dynamically generate the stylesheet, and randomly choose $image in that file. Then you’d inject your stylesheet <link …> via wp_enqueue_scripts hook (yes, wp_enqueue_scripts), and enqueue with wp_enqueue_style.