Search code examples
phpcsswordpressfilepathglob

How can I convert an absolute file path to one CSS can use?


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.


Solution

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