Link to a PDF With a Preview Image Using ACF

Quick Summary
- Output a new-tab link to a PDF from an ACF File field, showing its preview image if one exists or the file URL otherwise.
- The d_file field returns a File ID, and a pdf_thumbnail Image field on the attachment is read by passing that ID to get_field().
- Whether the PDF opens or downloads depends on the browser, and the file URL should also pass through esc_url() for safer output.
This snippet uses Advanced Custom Fields (ACF) to link to a PDF attached to a WordPress post. If you’ve given the PDF its own preview image, the link shows that image; otherwise it shows the file URL as text. The link opens in a new tab.
It relies on two ACF fields. Change these two names to match your own:
d_file: a File field on the post, with Return Format set to File ID.pdf_thumbnail: an Image field on the media file itself (a field group with the location rule Attachment), with Return Format set to Image ID.
Put the code in the template that displays the post, such as single.php, inside the loop.
<?php
$file = get_field( "d_file" );
if( $file ) {
$file_url = wp_get_attachment_url( $file );
$file_thumb = get_field( "pdf_thumbnail", $file );
if( $file_thumb ) {
$file_thumb_details = wp_get_attachment_image_src( $file_thumb,"full" );
echo "<a target='_blank' href='{$file_url}'><img src='" . esc_url( $file_thumb_details[0] ) ." '/></a>";
}else{
echo "<a target='_blank' href='{$file_url}'>{$file_url}</a>";
}
}
?>How it works
get_field( "d_file" )returns the attachment ID of the uploaded PDF, andwp_get_attachment_url()turns it into the file URL.get_field( "pdf_thumbnail", $file )passes the attachment ID as the second argument, so ACF reads the image field from the PDF’s attachment rather than from the post.wp_get_attachment_image_src()returns the preview image in thefullsize; index0is its URL.- If the post has no file, nothing is printed.
Whether the PDF opens in a browser tab or downloads depends on the visitor’s browser. For safer output, pass $file_url through esc_url() as well, and add alt text to the preview image.
Related articles
- outputting an ACF image field by ID: the same wp_get_attachment_image_src() pattern, with image sizes
- checking that ACF is active: keeps get_field() from breaking the template without the plugin
- why I still use ACF for custom websites: where field-driven snippets like this fit

