Using file_exists to check file in Uploads

Context: For a site’s images used in a particular section, each post relies on a base name put into meta data, which then is used with automatic extensions to generate large images, gallery thumbnail images, and an index page thumbnail as well.

For example, if Example_Name is the base name, then:
Example_Name_2-LG.jpg is the second large image in the series
Example_Name_2_SM.jpg is the corresponding second gallery thumbnail image
Example_Name_IN.jpg is the index thumbnail chosen to represent the set

By using meta data and PHP conditionals, all the client has to do is put in the base name once and upload the appropriately named images to the Uploads folder, and the page template fills in the blanks.

All this is working fine, with one catch. There are seven slots for the thumbnails, and the page displays all of the thumbnail divs, even if there are less than seven thumbnail images in the Uploads folder.

I’d like to wrap each thumbnail div with a conditional that uses file_exists to check for the existence of thumbnail images actually in the Uploads folder, so that if the named image doesn’t exist at the indicated file path, the corresponding empty div (and its hyperlink) won’t appear.

I’ve tried constructing absolute paths using the wp_uploads_dir function, as well as bloginfo('template_directory') and even the deprecated TEMPLATEPATH, but have only succeeded in generating PHP errors. I’m assuming this is a path problem or something particular I don’t understand about the PHP function file_exists.

Page blow-up example using wp_upload_dir:

<?php 
    $upload_dir = wp_upload_dir(); 
    if ( file_exists( echo $upload_dir['baseurl'] . "https://wordpress.stackexchange.com/" . echo get_post_meta($post->ID, '_meta_example_name', true) . '_7_SM.jpg') ) {
?>
    <div id="thumb7" class="thumb">  <!-- Should appear only when Example_Name_7_SM.jpg exists -->
        ...
    </div>

<?php } ?>

Any suggestions appreciated.

4 Answers
4

You can’t use a file url in file_exists() like this:

file_exists( "http://example.com/wp-content/uploads/Example_Name_2_SM.jpg" );

You should rather use an absolute file path, for example:

file_exists( "/absolute/path/to/wp-content/uploads/Example_Name_2_SM.jpg" );

Then you should try

$meta = get_post_meta( $post->ID, '_meta_example_name', true );
$file = $upload_basedir . "https://wordpress.stackexchange.com/" . $meta . '_7_SM.jpg';
if ( file_exists( $file ) ) {
   //...
}

where

$upload_basedir = WP_CONTENT_DIR . '/uploads';

or

$upload_dir = wp_upload_dir();
$upload_basedir = $upload_dir['basedir'];

Leave a Comment