0

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>

2 Answers 2

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

2
  • Using hardcoded relative url with pretty permalinks activated chances are image will not found.
    – gmazzap
    Commented Jul 25, 2013 at 23:57
  • @G.M. : Yep, you are right. It should not be using relative links either.
    – s_ha_dum
    Commented Jul 26, 2013 at 0:12
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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