user2120881 user2120881 - 1 year ago 82
PHP Question

Alternative of file_exists function for Wordpress

I have uploaded images into a directory inside my theme folder and trying to use file_exists to output the images.

Not all my posts have images so that is why I'm using the file_exists function.

I am not getting the desired results and would love some insight on this issue.

$preGetImage = get_template_directory_uri();
$vendorPhotoLogo = $preGetImage."/img/vendorimages/logo-".$vendor->acctno.".png";
$vendorPhotoImg = $preGetImage."/img/vendorimages/img-".$vendor->acctno.".png";

echo '<img src="'.$vendorPhotoImg.'"/>';

echo '<img src="'.$vendorPhotoLogo.'"/>';

Answer Source

Let me explain to help you out:

file_exists() runs on the server side to see if a file exists on the server's hard disk. Since it runs on the server side, you need to check it via an absolute path to the folder where the file exists.

Stay with me....

When you run if(file_exists($vendorPhotoImg)), PHP checks if the specified file exists on the server's hard drive. If yes, then it runs the code within the code block, i.e. the img HTML is rendered out to the browser.

For checking if the file exists, you have to use the absolute path to the server's hard drive location. You use get_template_directory() to get the folder path for your theme.

But wait, you need the URL path to the image location for the front-end. To get the absolute path to the image's URI, get_template_directory_uri().

Here's the code you need:

$theme_directory = get_template_directory();
$theme_uri       = get_template_directory_uri();

$vendorPhotoLogo = '/img/vendorimages/logo-' . $vendor->acctno . '.png';
$vendorPhotoImg  = '/img/vendorimages/img-' . $vendor->acctno . '.png';

if ( file_exists( $theme_directory . $vendorPhotoImg ) ) {
    printf( '<img src="%s"/>', esc_url( $theme_uri . $vendorPhotoImg ) );

if ( file_exists( $theme_directory . $vendorPhotoImg ) ) {
    printf( '<img src="%s"/>', esc_url( $theme_uri . $vendorPhotoLogo ) );

Notice how the file_exists() uses the theme directory and the img source uses the URI.

A couple of notes for you:

  1. The code uses esc_url() to sanitize the URL before sending it out to the browser.
  2. I prefer printf() over echo and concatenating strings in this edge case. You can use what you want here.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download