I’m trying to display a randomly-chosen background image on a WordPress site. My strategy is to inline the style
attribute of the <html>
element, like so:
<html style="background:#e8e6da url(<?php
$bg_imgs = glob(get_template_directory().'/backgrounds/*.jpg');
shuffle($bg_imgs);
echo $bg_imgs[0]; ?>) left top fixed">
On my local server, this outputs
<html style="background:#e8e6da url(C:xampphtdocsmysite/wp-content/themes/my_theme/backgrounds/paper2.jpg) left top fixed">
…which the browser doesn’t like because it’s asking to fetch a local resource. Even if this wouldn’t be a problem once the site is live, I only need a relative path to the image file.
So I was about to mess with using substr()
to chop off the unneeded part of the path, but I can’t be sure, depending on where the site is deployed, what get_template_directory()
will return. I don’t want to hard-code anything that might vary.
What’s the best strategy for returning a random image path relative to the site URL? I’m happy to ditch the above if there’s something better.
You could try getting the document root and chopping it off the beginning of your full path:
I know this is not foolproof – it’s just an idea.
Try
get_bloginfo('template_url')
instead, or probablyget_template_directory_uri()