1

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.

1
  • 1
    What is the problem? Commented Jun 30, 2016 at 23:55

1 Answer 1

2

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()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.