Support » Plugins » Hacks » Checking if an image exists within WP?

  • Hi,

    I’m trying to get a rotating sidebar background image. I’m trying to find a way to see if an image file exists through a relative path. Using an absolute path, this works:

    if( fopen(“http://etc”, “r”) ){
    echo foo;
    }

    But I can’t seem to find a way to make it work with a relative path. Reason is that it really slows down pageload time for it to check the url as an “outside” url (http://www.etc…).

    Help?

    Thanks

Viewing 5 replies - 1 through 5 (of 5 total)
  • Because of the way that WordPress (and other CMS systems) work, relative paths will never work in all cases. Because the location of the current page, as seen by the browser and Apache, will change depending on what sort of content you are looking at. Thus the need for absolute paths.

    You don’t need to use paths that start with http://. Just start with a slash and indicate the path from the root web folder. In other words, if you have installed WP in the root web folder, you can refer to
    /wp-content/uploads/2011/01/my_image.jpg That is seen as an absolute path.

    You don’t need to have http://example.com/wp-content/uploads/2011/01/my_image.jpg

    if you are working in PHP, even better you can say

    <img src="<?php bloginfo('template_directory'); ?>/images/my_image.jpg" alt="" /> if the image is in the theme’s images folder

    or

    <img src="<?php echo WP_CONTENT_URL; ?>/uploads/2011/01/my_image.jpg" alt="" /> if its in the uploads folder.

    Using those, your code is good even if you later move WP to a different location or domain.

    You’ll need the local path to check if the file exists, something like this should work..

    If the image is in the root of the theme.

    if( file_exists( TEMPLATEPATH . '/file.jpg' ) ) {
        // do whatever
    }

    If in an images folder inside the theme.

    if( file_exists( TEMPLATEPATH . '/images/file.jpg' ) ) {
        // do whatever
    }

    http://php.net/manual/en/function.file-exists.php

    Hope that helps.

    Thanks. That works for if_exists().

    Is it possible to do something like $foo = TEMPLATEPATH.”filename.jpg”;

    I’m sure there’s some syntax for that, I just haven’t found it. I’m new to hacking WP, but fine with PHP.

    yes

    Is it possible to do something like $foo = TEMPLATEPATH.”filename.jpg”;

    Is it possible to store that data in a variable? Yes of course it is, this would be a perfectly valid use..

    $foo = TEMPLATEPATH . "/filename.jpg";
    if( file_exists( $foo ) ) {
        // do whatever
    }

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Checking if an image exists within WP?’ is closed to new replies.