Support » Plugins » Hacks » PHP file_exists function won't work

  • I have a WordPress website (still running locally) with different pages. I want each page to display its own unique header image (using the page name as image name), and am able to get that part working smoothly. But, when no header image is available (yet) for that specific page, I want to display a placeholder image. To do this, I use the file_exists function. It doesn’t work, however. I use this code (note: this is a simplified/altered version. I don’t bother you with the full code since I don’t even get this simple code to work).

    <img src="<?php
    if (file_exists('/images/headers/home.jpg')) {
        echo '/wp-content/themes/theme/images/headers/home.jpg';
    }
    else {
        echo '/wp-content/themes/theme/images/headers/placeholder.jpg';
    }
    ?>" />

    The problem is: even though home.jpg exists, it keeps showing me the placeholder.jpg.

    I already tried following file paths:
    – Full link
    – /wp-content/themes/theme/images/headers/home.jpg
    – /images/headers/home.jpg
    – home.jpg

Viewing 2 replies - 1 through 2 (of 2 total)
  • file_exists works best with within the local filesystem and with absolute paths, not URLs (at least in general). So you could try something like this:

    if( file_exists( ABSPATH . 'wp-content/themes/theme/images/headers/home.jpg' ) ) {
    }
    Dion

    (@diondesigns)

    Assuming your code is in the theme’s functions.php file, I’d suggest trying the following:

    if (file_exists(dirname(__FILE__) . '/images/headers/home.jpg')) {

    If you’re using a child theme, this will only work if the image is also part of the child theme.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘PHP file_exists function won't work’ is closed to new replies.