如果file_exists在PHP问题wordpress


if file_exists in PHP issue wordpress

我正在尝试创建检查图像是否存在于我的网站上的代码,如果不显示默认图像。在一种情况下,我知道文件存在,并且可以使用我希望file_exist使用的变量将它链接到文件!

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

谢谢。

PHP的file_exists不与URL一起使用,它用于服务器本身的文件路径。没问题。首先,我们需要得到主题模板目录的路径:

$templateDirectory = get_template_directory();

假设您提供的链接在您自己的服务器上,那么您的图像的完整路径是

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

我们现在可以检查您的图像是否存在以下

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

希望这对你有帮助。参考文档中file_exists和get_template_directory()