简体   繁体   English

无法使PHP file_exists工作

[英]Trouble getting PHP file_exists to work

I'm trying to get a thumbnail to link to a PDF of the same name if the PDF exists, but to not link to anything if the PDF doesn't exist. 我正在尝试获取缩略图以链接到具有相同名称的PDF(如果PDF存在),但是不链接到任何不存在的PDF(如果不存在)。 Here's the code I have: 这是我的代码:

<?php 
if ( function_exists('has_post_thumbnail') && has_post_thumbnail() ) {
$full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full') ;
$pdf = substr_replace($full_image_url , 'pdf', strrpos($full_image_url[0] , '.') +1);

$filename = $pdf[0];
if (file_exists($filename)) {
echo '<a href="' . $pdf[0] . '" title="' . the_title_attribute('echo=0') . '" . target="_blank" >';
the_post_thumbnail('Full Size');
echo '</a>';
  }
else {
echo "The file $filename exists";
  }
 }
?>

Currently, the else statement is just to prove whether or not it's finding the file. 当前,else语句只是为了证明它是否正在查找文件。 Which it seems to, as it displays The file http://localhost/AWAD/wp-content/uploads/2012/03/+D.pdf exists . 看起来像它看起来一样The file http://localhost/AWAD/wp-content/uploads/2012/03/+D.pdf exists And if I get rid of the conditional, the post thumbnail displays with a link to the PDF. 而且,如果我摆脱了条件,那么将显示帖子缩略图,并带有指向PDF的链接。 I just can't get the conditional to work. 我就是没有条件工作。

Can anyone spot why it's not working? 谁能发现它为什么不起作用?

您应该在FS上将路径传递到file_exists ,现在正在传递URL

I'm pretty sure file_exists wants a full file path, not a URL. 我很确定file_exists想要完整的文件路径,而不是URL。 So, you'll probably want to use the WordPress wp_uploads_dir function to get the base path to your uploads directory and then append the rest of the path to the end of that and then pass that string to file_exists . 因此,您可能需要使用WordPress的wp_uploads_dir函数获取上载目录的基本路径,然后将其余路径附加到该目录的末尾,然后将该字符串传递给file_exists Hopefully that makes sense. 希望这是有道理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM