我在 WordPress 上传文件夹中创建了一个目录,供最终用户通过 ftp 批量上传照片。图像编号为 1.jpg、2.jpg...等。我已成功生成图像网址,但现在我想测试空网址 - 即如果“8.jpg”不存在,则显示占位符图像而是从主题的图像文件夹中。
我正在尝试使用 file_exists(),但这每次都会返回 false 并且始终显示占位符图像。如有任何建议,我们将不胜感激。
<?php while ( have_posts() ) : the_post();
// create url to image in wordpress 'uploads/catalogue_images/$sale' folder
$upload_dir = wp_upload_dir();
$sub_dir = $wp_query->queried_object;
$image = get_field('file_number');
$image_url = $upload_dir['baseurl'] . "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG"; ?>
<?php if(file_exists($image_url)){
echo '<img src="' . $image_url . '" alt="" />';
} else {
//placeholder
echo '<img src="' . get_bloginfo("template_url") . '/images/photo_unavailable.jpg" alt="" />';
} ?>
<?php endwhile; ?>
最佳答案
PHP file_exists
函数主要 expects an internal server path to the file to be tested 。这通过example变得显而易见。 .
幸运的是,我们看到wp_upload_dir()
为我们提供了几个有用的值:
- 'path' - base directory and sub directory or full path to upload directory.
- 'url' - base url and sub directory or absolute URL to upload directory.
- 'subdir' - sub directory if uploads use year/month folders option is on.
- 'basedir' - path without subdir.
- 'baseurl' - URL path without subdir.
- 'error' - set to false.
我已经将我们想要使用的内容加粗了。使用这两个值,您必须生成两个变量,一个用于外部 URL,一个用于内部文件路径:
$image_relative_path = "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG";
$image_path = $upload_dir['basedir'] . $image_relative_path;
$image_url = $upload_dir['baseurl'] . $image_relative_path;
然后使用 file_exists($image_path)
而不是 file_exists($image_url)
。
注意
与 PHP >= 5.0.0 上的 PHP 注释一样,您 can indeed use file_exists
with some URLs ,但是 http://
协议(protocol)是 not supported for the stat()
function (这是 file_exists
使用的。)
关于php - 使用 file_exists() 检查 WordPress 上传文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27865151/