I’m trying to automatically switch my background image in wordpress depending on the visitors screen size. If he/she has a big screen, he/she gets the big version of the image. If the screen is small, he/she gets the smaller version. (Just for loading time reduction. The image will be resized to fill the screen afterwards, but that’s already working.)
What isn’t working is the check wether or not the smaller version even exists. If it doesn’t exist, the script should fall back to the bigger version and just use that image. I get a background image, but it’s only the big one (wordpress field name “BG_value”. The url of the small image is stored in “BG_value-medium”).
The images DO exist and the paths passed through the wordpress fields are fine, too, so that is NOT the problem. :/
But, without further ado, I present you the code (from my header.php from wordpress).
<body>
<!-- WordPress Loop -->
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<script type="text/javascript">
if (($(window).width() < 1340) && (<?php
if(file_exists(bloginfo('template_url').get_post_meta($post->ID, 'BG_value-medium', $single = true))){
echo "true";
}else{
echo "false"; } ?> )){
<?php $bgimg = get_post_meta($post->ID, 'BG_value-medium', $single = true); ?>
} else {
<?php $bgimg = get_post_meta($post->ID, 'BG_value', $single = true); ?>
}
</script>
<div id="bgimage"> <img class="stretch" src="<?php bloginfo('template_url'); ?><?php echo $bgimg; ?>" alt="" /> </div>
<?php endwhile; endif; ?>
I’m sorry if this looks a bit messy, I’ve been working on this for the last few hours, changing it over and over again.
Any ideas what’s going wrong here? Check out the page
You have a big logical error in this. You want to set the bg image with an javascript function, but you never try to set it with javascript, only with an php echo. Take a look at the sourcecode of this javascript snippet in your browser, and you will see what i mean.
You should store the image-pathes in javascript variables inside the
then
andelse
, and use them to set the bg image.Untested:
I’ve tried to clean up that mess to see what is happening. The following is untested, but if something doesn’t work you can now atleast see why it doesn’t work.