Reputation: 3573
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:\xampp\htdocs\mysite/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.
Upvotes: 1
Views: 274
Reputation: 57316
You could try getting the document root and chopping it off the beginning of your full path:
$docRoot_len = strlen($_SERVER['DOCUMENT_ROOT']);
$bg_imgs = glob(get_template_directory().'/backgrounds/*.jpg');
shuffle($bg_imgs);
echo substr($bg_imgs[0], $docRoot_len);
I know this is not foolproof - it's just an idea.
Upvotes: 1
Reputation: 360692
Try get_bloginfo('template_url')
instead, or probably get_template_directory_uri()
Upvotes: 1