【发布时间】:2025-12-09 23:45:01
【问题描述】:
我正在尝试使用if (file_exists() 检索保存在 wp-uploads 目录中的 WP 帖子的图像,但它无法识别文件路径。
对于每个帖子,最多有 8 张图片可用。每个图像的文件名末尾都有字母 a-g(或没有),并有 str_replace 来替换文件名中的某些字符。
如果存在,我需要显示每个图像,如果不存在,则不返回任何内容。因此,如果帖子与末尾带有 b、d 和 f 的图像相关联,它只会显示这三个。
我已经在不使用 (file_exists()) 的情况下进行了测试,它能够通过简单的回声为每个图像拾取图像 - 但似乎无法识别 $img 路径。
我有点 php 菜鸟,所以任何帮助将不胜感激......
$uid = get_post_meta (get_the_ID(), 'Unique number', true);
$root ="/wp-content/uploads/2016/Collection/";
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$img = $root.$path.".jpg";
$imga = $root.$path."a.jpg";
$imgb = $root.$path."b.jpg";
$imgc = $root.$path."c.jpg";
$imgd = $root.$path."d.jpg";
$imge = $root.$path."e.jpg";
$imgf = $root.$path."f.jpg";
$imgg = $root.$path."g.jpg";
if (file_exists($img)) { echo "<img src='".$root.$path.".jpg' />"; } else { echo ""; }
if (file_exists($imga)) { echo "<img src='".$root.$path.".jpg' />"; } else { echo ""; }
if (file_exists($imgb)) { echo "<img src='".$root.$path."b.jpg' />"; } else { echo ""; }
if (file_exists($imgc)) { echo "<img src='".$root.$path."c.jpg' />"; } else { echo ""; }
if (file_exists($imgd)) { echo "<img src='".$root.$path."d.jpg' />"; } else { echo ""; }
if (file_exists($imge)) { echo "<img src='".$root.$path."e.jpg' />"; } else { echo ""; }
if (file_exists($imgf)) { echo "<img src='".$root.$path."f.jpg' />"; } else { echo ""; }
if (file_exists($imgg)) { echo "<img src='".$root.$path."g.jpg' />"; } else { echo ""; }`
【问题讨论】:
标签: php wordpress file-exists