Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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">

<?php

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

?>

$(document).ready(function(){

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

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

});
</script>
share|improve this question
add comment

2 Answers

  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. –  G. M. 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
add comment

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" ....

in:

<?php
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
add comment

Your Answer

 
discard

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.