Reputation: 33
I have created a directory in Wordpress uploads folder for end user to bulk upload photos via ftp. Images are numbered 1.jpg, 2.jpg... etc. I've generated the image urls successfully, but now I want to test for empty urls - i.e. if "8.jpg" doesn't exist, show a placeholder image from the theme's images folder instead.
I'm trying to use file_exists(), but this returns false every time and always displays the placeholder image. Any suggestions would be appreciated.
<?php while ( have_posts() ) : the_post();
// create url to image in wordpress 'uploads/catalogue_images/$sale' folder
$upload_dir = wp_upload_dir();
$sub_dir = $wp_query->queried_object;
$image = get_field('file_number');
$image_url = $upload_dir['baseurl'] . "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG"; ?>
<?php if(file_exists($image_url)){
echo '<img src="' . $image_url . '" alt="" />';
} else {
//placeholder
echo '<img src="' . get_bloginfo("template_url") . '/images/photo_unavailable.jpg" alt="" />';
} ?>
<?php endwhile; ?>
Upvotes: 2
Views: 8513
Reputation: 16502
The PHP file_exists
function mainly expects an internal server path to the file to be tested. This is made obvious with the example.
Fortunately, we see that wp_upload_dir()
gives us several useful values:
- 'path' - base directory and sub directory or full path to upload directory.
- 'url' - base url and sub directory or absolute URL to upload directory.
- 'subdir' - sub directory if uploads use year/month folders option is on.
- 'basedir' - path without subdir.
- 'baseurl' - URL path without subdir.
- 'error' - set to false.
I've bolded what we want to use. Using these two values, you have to generate two variables, one for the external URL and one for the internal file path:
$image_relative_path = "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG";
$image_path = $upload_dir['basedir'] . $image_relative_path;
$image_url = $upload_dir['baseurl'] . $image_relative_path;
Then use file_exists($image_path)
instead of file_exists($image_url)
.
As with the PHP notes on PHP >= 5.0.0, you can indeed use file_exists
with some URLs, however the http://
protocol is not supported for the stat()
function (which is what file_exists
uses.)
Upvotes: 7
Reputation: 1373
You have to use an internal path for checking if a file exists.
So use $upload_dir['path']
instead $upload_dir['baseurl']
[path] - base directory and sub directory or full path to upload directory.
http://codex.wordpress.org/Function_Reference/wp_upload_dir
Upvotes: 1