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>
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>
$
alias as WordPress loads
jQuery in "No Conflict" mode.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.
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.