Random background images in wordpress?

I am using WP 3.5.1, twenty twelve child theme and PHP 5.2 on my server.
I am trying to use a php script(that works on my other websites) in order to get random background-image but it’s not working:

CSS:

Read More
body {
    background: url(<?php include ("bg.php"); echo $selectedBg; ?>) no-repeat fixed;
}

PHP:

<?php
  $bg = array('1.jpg','2.jpg','3.jpg','4.jpg','5.jpg');
  $i = rand(0, count($bg)-1);
  $selectedBg = "$bg[$i]";
?>

my php file is in the same folder as the jpg’s.
Any ideas?

No errors. If I use background: url(1.jpg); (instead of php) it works fine but obviously shows 1 image.

Related posts

Leave a Reply

5 comments

  1. Small solution:

    We know that he have 5 images on the server:

    '1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'
    

    So quick tip:

    <body style="background: url('pahttoimages/<?= rand(1, 5) ?>.jpg') no-repeat top center;">
    
  2. As far as I can see, your code is valid.

    Except, you should really write the last line like:

    $selectedBg = $bg[$i];
    

    No need for quotes here.


    I suspect this is what is causing the error:

    my php file is in the same folder as the jpg’s. Any ideas?

    The background-image needs to be relative to the template-file you are using, not the PHP-file. You script will only work if the images are located in the same folder as the template-slices.

    In my WP-installation, I have a template located in /wp-content/themes/mytemplate/ and template-graphics located in /wp-content/themes/mytemplate/images/. If I were to use your script, I would need to preappend /images/ before all the backgrounds in your array.


    By the way, you should consider installing Firebug on Firefox and inspect the source. Is the background-name parsed into the template? Does loading the image return a 404 not found-error? Is the location and path correct?


    background-image: url(<?php include ("bg.php"); echo $selectedBg; ?>);
    background-position: fixed;
    background-repeat: no-repeat;
    
  3. Do this:

    // bg.php
    <?php
    
    return array(
        '1.jpg',
        '2.jpg',
        '3.jpg'
    );
    
    // WordPress CSS
    <?php
    $imageUrls = include('bg.php');
    $imageUrl = $imageUrls[ array_rand($imageUrls) ];
    ?>
    .someClass {
        background-image: url(<?php echo $imageUrl ?>);
    }