2

I've been refraining from posting in here as I feel it's such a simple question that's been answered many times over and over again. I know this because I've read through countless posts people have made asking the same thing, but for some reason I am unable to get the same results.

What I need is fairly simple. I need to display all of the images from a directory relevant to the current page and parent page in a template file for a WordPress page.

First of all, let me point out that I am able to get this code working outside of WordPress so I am lead to believe that there is an issue with the way content is being delivered within the template file.

This is the code that I have:

<?php
$page_parent = get_the_title($post->post_parent);
$current_page = get_the_title($post);
$upload_dir = wp_upload_dir();                  

$dir = $upload_dir['baseurl'].'/assets/'.$page_parent.'/'.$current_page.'/';

$files = glob($dir.'{*.jpg,*.png}', GLOB_BRACE);
foreach ($files as $image){
    echo '<img src="'.$dir.$image.'" alt="'.$image.'" />';
};

var_dump($files); // This displays array(0) { }
var_dump($image); // This display NULL              
echo $dir; // This works to display the correct URL.
?>

The above code is not displaying any of the images and even if I strip out the <img> tags and try a simple echo $image; it still won't even show me the filenames. However, echo $dir; works and displays the correct url which is a direct path to http://localhost:8888/wordpress/wp-content/uploads/assets/Photography/Holga/

When I do var_dump($files) all I get is array(0) { } and when I do var_dump($image) all I get is NULL yet outside of WordPress it will display the data.

I'm aware that the page names may have capitalised titles so I have kept the folder structure consistent, but as I mentioned I am able to make this work outside of WordPress which is killing me!

Does anyone have any suggestions or reasons why this may not work inside of a WordPress page template?

Thanks in advance!

4

1 回答 1

1

在从 返回的数组中wp_upload_dir(),您想使用$upload_dir['basedir']而不是$upload_dir['baseurl']。这将返回上传文件夹的路径,而不是它的 URL。

您没有得到任何结果,因为您没有将有效路径传递给glob(). 从文档中的注释

注意:此功能不适用于远程文件,因为要检查的文件必须可以通过服务器的文件系统访问。

于 2013-05-05T20:53:32.867 回答