WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This comes from the footer.php file of a wordpress theme I would like to modify. I want one of five images to load on refresh instead of 1.jpg every time.

<script type="text/javascript">


if((is_archive()) || (is_author()) || (is_category()) || (is_home()) || (is_single()) || (is_tag()) || ($posttype == 'post')  ) {
        $name = "news-and-information";
        $name = $wp_query->post->post_name;



        var imgPath = '/wp-content/themes/nexus/img/page-headers/<?php echo $name; ?>/1.jpg';

        $('.subheader-wrapper').css('background-image', ('url("'+imgPath+'")'));

share|improve this question
  1. That theme should not be using the $ alias as WordPress loads jQuery in "No Conflict" mode.
  2. I can only assume the theme is loading its own jQuery, which is pretty bad form.
  3. The theme should really be registering and enqueuing the script properly rather than just shoving code into the footer.

However, all other things equal and if your images are named numerically, then changing this:

var imgPath = '/wp-content/themes/nexus/img/page-headers/<?php echo $name; ?>/1.jpg';

To this:

var imgPath = <?php echo site_url(); ?>/wp-content/themes/nexus/img/page-headers/<?php echo $name; ?>/<?php echo rand(1,5); ?>.jpg';

And it should echo images 1.jpg through 5.jpg randomly.

share|improve this answer
Using hardcoded relative url with pretty permalinks activated chances are image will not found. – gmazzap Jul 25 '13 at 23:57
@G.M. : Yep, you are right. It should not be using relative links either. – s_ha_dum Jul 26 '13 at 0:12

Easy way. with no js at all.

Somewhere in you template there is a html tag, probably a div, with class 'subheader-wrapper'.

So, name images numerically as @s_ha_dum says then change your html from

<div class="subheader-wrapper" ....


if( ! is_singular() || ($posttype == 'post')  ) {
    $name = "news-and-information";
} else {
    global $wp_query;
    $name = $wp_query->post->post_name;
var img = get_template_directory_uri() . '/img/page-headers/' . $name . rand(1,5) . '.jpg';
<div class="subheader-wrapper" style="background-image:url(<?php echo $imgpath; ?>)" ...

I've used get_template_directory_uri() instead of relative url, like you do, because using hardcoded relative url with pretty permalinks activated chances are image will not found.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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