Link to PDF instead of Attachment page
By default, WordPress will link to what is referred to as an ‘attachment page’ when including PDFs in search results.
See also: Link to file instead of Attachment page
If you would like to instead link directly to the file you can add the following to your theme’s functions.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Automatically convert permalinks to PDFs in search results to the PDF itself, not the Attachment page | |
function my_force_direct_pdf_links( $permalink ){ | |
global $post; | |
if ( is_search() && 'application/pdf' == get_post_mime_type( $post->ID ) ) { | |
// if the result is a PDF, link directly to the file not the attachment page | |
$permalink = wp_get_attachment_url( $post->ID ); | |
} | |
return esc_url( $permalink ); | |
} | |
add_filter( 'the_permalink', 'my_force_direct_pdf_links' ); | |
add_filter( 'attachment_link', 'my_force_direct_pdf_links' ); |
Or you can modify your search results template like so:
Note: this is a generalized example. Your search template will likely look very different than this one, but the sample code provides the conditional necessary to instead output the link directly to the PDF instead of the attachment page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php if ( have_posts()) : while (have_posts() ) : the_post(); ?> | |
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> | |
<?php | |
$permalink = get_permalink(); | |
if( 'attachment' == get_post_type() ) { | |
// if the result is a PDF, link directly to the file not the attachment page | |
$permalink = wp_get_attachment_url( $post->ID ); | |
} | |
?> | |
<h2> | |
<a href="<?php echo esc_url( $permalink ); ?>"><?php the_title(); ?></a> | |
</h2> | |
<?php the_excerpt(); ?> | |
</div> | |
<?php endwhile; else : ?> | |
<p>There were no posts found.</p> | |
<?php endif; ?> |