【发布时间】:2014-05-17 14:17:33
【问题描述】:
我有一个功能,它打开一个预先指定的目录,在目录中创建一个图像文件数组,然后从数组列表中提取一个随机图像名称以回显到网页。问题是有时它实际上并没有提取图像名称。
这是 php 代码:
<?php
$actualpath = get_stylesheet_directory_uri() . "/img/banners/";
// open this directory
$myDirectory = opendir("wp-content/themes/beautysalon/img/banners/");
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// close directory
closedir($myDirectory);
function getRandomFromArray($ar) {
mt_srand( (double)microtime() * 1000000 ); // php 4.2+ not needed
$num = array_rand($ar);
return $ar[$num];
}
$randomPicture = getRandomFromArray($dirArray);
?>
以及我用来在网页上实际显示图像的代码:
<?php
if ( !is_front_page() ) {
echo '<img src="' . $actualpath . $randomPicture . '"/>';
};
?>
当代码运行时,它最终会回显如下内容:
<src="http://sitename.com/directorypath/image.png" />
这正是我打算做的。但是当它不起作用时,由于某种原因它不会拉取图像名称并最终输出类似这样的内容,从而导致图像损坏:
<src="http://sitename.com/directorypath/" />
这几乎就像php在页面内容生成之前还没有来得及运行函数,但我认为php总是在页面渲染之前完全执行。
Working example of the PHP script in action can be found here.
脚本在除主页和联系页面之外的所有页面上运行。
【问题讨论】: