WordPress:使用glob()返回一个空数组 [英] Wordpress: Using glob() returns an empty array
问题描述
我正在尝试从指定目录中提取所有图像,然后显示它们。我在常规网站上使用了以下代码,并且可以正常运行
I am trying to pull all images from a specified directory and then display them. I used the below piece of code in a regular website and it works
<?php $dirname = "images/tile/tile2/";
$images = glob($dirname."*.jpg");
foreach($images as $image) {
echo '<li><img src="'.$image.'" /><br /></li>';
}?>
我现在已经将这段代码移到了wordpress网站上,并得到了一个空数组。 / p>
I have now moved this code and modified it to a wordpress site and I get an empty array.
<?php $dirname = get_template_directory_uri()."/images/tile/tile1/";
$images = glob($dirname. "*.jpg");
//$images = glob($dirname."*. {jpg}", GLOB_BRACE); - tried with GLOB_RACE
foreach($images as $image) {
echo '<li><img src="'.$image.'" /><br /></li>';
}?>
第二个代码
<?php define('ACCREDPATH', get_template_directory_uri() . '/images/tile/tile1/');
$images = glob(ACCREDPATH. "*.jpg");
//$images = glob(ACCREDPATH. "*. {jpg}", GLOB_BRACE); - tried with GLOB_RACE
foreach($images as $image) {
echo '<li><img src="'.$image.'" /><br /></li>';
}?>
- 我已检查图像是否在文件夹中
- 我已经完成了var_dump,并且获得了正确的路径。
- 在glob($ images)上的var_dump给出了array(0){}
- 我也一直在寻找与此问题相关的其他线程仍然什么都没有
- I have checked that the images are in the folder
- I have done a var_dump and I am getting the right path.
- var_dump on the glob($images) gives array(0){ }
- I have also looked for other threads with this issue and still nothing
请提供任何帮助。
推荐答案
glob
适用于本地路径而不是URL。该功能需要能够访问服务器无法远程访问的文件系统(通过URL)。
glob
works on a local path rather than a URL. The function needs to be able to access the server's filesystem which it can't do remotely (via URL).
http://php.net/manual/en/function.glob.php
您在工作代码中提供的路径是相对的。之所以起作用,是因为它既可以用作文件路径,也可以用作URL。
The path you're providing in your working code is relative. It functions because it can be used as both a file path and a URL.
要使用主题的绝对路径获得相同的结果,您需要使用 get_template_directory()
。在提供的示例中,我使用 get_template_directory()
获取绝对路径,使用 get_template_directory_uri()
输出为网址。
To achieve the same result with an absolute path to your theme you'll need to use get_template_directory()
. In the example provided I'm using get_template_directory()
to get the absolute path and get_template_directory_uri()
to output as a URL.
示例:
$theme_img_path = '/images/tile/tile1/';
$images = glob( get_template_directory() . $theme_img_path . '*.jpg' );
foreach ( $images as $image ) {
// Convert the filename into an absolute URL.
echo get_template_directory_uri() . $theme_img_path . basename( $image );
}
第二次尝试中还有一个值得指出的问题。您不能使用函数来设置常量的值。
There's another issue in your second attempt that's worth pointing out. You can't use a function to set the value of a constant.
这篇关于WordPress:使用glob()返回一个空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!