Atrag
Atrag

Reputation: 743

if file_exists in PHP issue wordpress

I am attempting to create code that checks if an image exists on my site and if not shows a default image. In one case I know the file exists and can get it to link to the file using the variable that I want file_exist to use!

$menuCategories = get_categories( array(
   'child_of' => $whichGrade,));

foreach ( $menuCategories as $menuCategory ) { ?>
   <?php
        $linktoicon = get_bloginfo('template_directory') ."/images/menuicon_".$menuCategory->slug.".png";
        if (file_exists($linktoicon)) {
           $iconref = $menuCategory->slug; 
        }else { 
            $iconref = "default";
        } ?>
           <a href='<?php echo $linktoicon;  ?>'> <?phpvar_dump($iconref); ?></a>
<?php }?>

$linktoicon` is "http://mybritishhelper.com/wp-content/themes/wpex-magtastico/images/menuicon_colours.png"

Thank you.

Upvotes: 1

Views: 59

Answers (1)

Fred Vollmer
Fred Vollmer

Reputation: 168

PHP's file_exists isn't used with URL's, it's used for paths to files on the server itself. Not a problem. First, we need to get the path to your theme's template directory:

$templateDirectory = get_template_directory();

Assuming that the link you provided is on your own server, the full path to your image is

$pathToImage = $templateDirectory . '/images/menuicon_colours.png';

We can now check if your image exists with the following

if (file_exists($pathToImage)) {
// Do stuff
}

Hope this helps. For reference, see the docs for file_exists and get_template_directory()

Upvotes: 2

Related Questions