我想在WordPress网站上显示一个随机选择的背景图像。我的策略是内联<html>
元素的style
属性,如下所示:
<html style="background:#e8e6da url(<?php
$bg_imgs = glob(get_template_directory().'/backgrounds/*.jpg');
shuffle($bg_imgs);
echo $bg_imgs[0]; ?>) left top fixed">
在我的本地服务器上,输出
<html style="background:#e8e6da url(C:'xampp'htdocs'mysite/wp-content/themes/my_theme/backgrounds/paper2.jpg) left top fixed">
…这是浏览器不喜欢的,因为它请求获取本地资源。即使这不会是一个问题,一旦网站上线,我只需要一个相对路径到图像文件。
所以我要用substr()
来切断路径中不需要的部分,但我不能确定,这取决于站点部署的位置,get_template_directory()
将返回什么。我不想硬编码任何可能变化的东西。
相对于站点URL返回随机图像路径的最佳策略是什么?如果有更好的方法,我很乐意放弃上面的方法。
您可以尝试获取文档根目录并将其从完整路径的开头截断:
$docRoot_len = strlen($_SERVER['DOCUMENT_ROOT']);
$bg_imgs = glob(get_template_directory().'/backgrounds/*.jpg');
shuffle($bg_imgs);
echo substr($bg_imgs[0], $docRoot_len);
我知道这不是万无一失的——这只是一个想法。
试试get_bloginfo('template_url')
,或者get_template_directory_uri()