Link to file instead of Attachment page

Last updated December 18, 2018 « Knowledge Base

By default, Media returned in search results will link to an Attachment page. Many themes do not have useful templates for Media and very often it makes sense to link directly to the file itself instead.

See also: Link to PDF instead of Attachment page

To customize your search results template to link directly to Media files instead of an Attachment page, add the following to your theme’s functions.php:

<?php
// Link directly to Media files instead of Attachment pages in search results
function my_search_media_direct_link( $permalink, $post = null ) {
if ( is_search() && 'attachment' === get_post_type( $post ) ) {
$permalink = wp_get_attachment_url( $post->ID );
}
return esc_url( $permalink );
}
add_filter( 'the_permalink', 'my_search_media_direct_link', 10, 2 );
view raw functions.php hosted with ❤ by GitHub
Fix Search on Your Site. No Coding Required!

Now you can utilize all of the content that's gone unrecognized by native WordPress search instantly with SearchWP

Get SearchWP