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!