如何检查WordPress中是否确实存在该文件?

时间:2019-07-06 04:20:00

标签: wordpress

在循环中,我使用以下代码检查文件是否确实存在

<?php 
if(has_post_thumbnail()) {
    $url = get_the_post_thumbnail_url();   
    $explode = explode('/', $url);
    $url = trim('../../'.basename(wp_get_upload_dir()['basedir']).wp_get_upload_dir()['subdir'].'/'.end($explode));
    echo $url;
    if( file_exists($url)) {
        $url = $url;
    } else {
        $url = '';
    }
} else {
    $url = get_template_directory_uri().'/assets/images/blog/layout-1/blog-thumbnail-1.jpg';
}                                          
?>
<img src="<?php echo $url; ?>" alt="blog thumb">

回显$url正在打印此URL:

  

../../ uploads / 2019/07 / 5e026bb1-b58b-3df0-ae5f-2acd7d808ff3.jpg

,但现在不起作用。我无法确定$url文件是否确实存在。

已更新:

if(has_post_thumbnail()) {                                                
    $url            = get_the_post_thumbnail_url();
    $explode        = explode('/', $url);
    $upload_dir     = wp_upload_dir();
    $upload_path    = $upload_dir['path'];
    $url            = $upload_path . '/' . end($explode);

    if(file_exists($url)) {
        $url = get_the_post_thumbnail('blog-thumb');
    } else {
        $url = get_template_directory_uri().'/assets/images/blog/layout-1/blog-thumbnail-1.jpg';
    }
} else {
    $url = get_template_directory_uri().'/assets/images/blog/layout-1/blog-thumbnail-1.jpg';
}                                                                                       
?>
<img src="<?php echo $url; ?>" alt="blog thumb">

1 个答案:

答案 0 :(得分:2)

让我们在下面尝试代码

$url = get_the_post_thumbnail_url();

$explode = explode('/', $url);
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['path'];

$url = $upload_path . '/' . end($explode);

var_dump(file_exists($url));die;

请仔细检查文件夹中的文件。