简体   繁体   中英

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";

    if(file_exists($vendorPhotoImg)){
      echo '<img src="'.$vendorPhotoImg.'"/>';
    }

    if(file_exists($vendorPhotoLogo)){
      echo '<img src="'.$vendorPhotoLogo.'"/>';
    }

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM