简体   繁体   中英

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. 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. Which it seems to, as it displays 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. 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. 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 . Hopefully that makes sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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