I am working on a website with some custom PHP.
The post uses “Custom Fields”, where the custom field “pdf_name” is added to the post when there is a PDF document to attach to it. The value would be the URL to that PDF.
If there is no PDF, this custom field is not used and thus gives no (URL) value.
To use this, I go into “single.php” to add a function like so:
<?php $pdf_name = get_post_meta($post->ID, 'pdf_name', true); ?>
Then I add the HTML:
<a class="pdfDownload" href="<?php bloginfo('url'); ?>/wp-content/uploads/<?php echo $pdf_name; ?>">PDF Download</a>
The HTML text link, “PDF Download”, will appear on all post displays, whether or not there is a PDF linked to it. This results in a 404 page if someone clicks the text link that has no PDF URL returned to it.
Request:
I want to hide this PDF text link if the $pdf_name function finds no PDF URL to use.
In other words, it finds and returns as no value.
or…
if it is easier, when there is no PDF URL value, replace the HREF HTML with a basic non-linked text like “No PDF Available”.
Note: I am using a Child theme, so the theme single.php file is duplicated there.
Can anyone help with this?
Thanks
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If the custom field will be always empty when there is no pdf file, you can check if it is not empty before displaying the link:
<?php
$pdf_name = get_post_meta($post->ID, 'pdf_name', true);
if($pdf_name) {
?>
<a class="pdfDownload" href="<?php bloginfo('url'); ?>/wp-content/uploads/<?php echo $pdf_name; ?>">PDF Download</a>
<?php
}
?>
But, if there is a possibility that the custom field can hold a value even if there is no actual pdf file attached, then you can check if the pdf file actually exists by its path before displaying the download URL:
<?php
$pdf_name = get_post_meta($post->ID, 'pdf_name', true);
$uploads_dir = wp_upload_dir();
$pdf_path = $uploads_dir['basedir'] . '/' . $pdf_name;
if(is_file($pdf_path)) { ?>
<a class="pdfDownload" href="<?php bloginfo('url'); ?>/wp-content/uploads/<?php echo $pdf_name; ?>">PDF Download</a>
<?php
}
?>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0