Link to file (e.g. PDF) instead of Attachment page
WordPress by default will link to an Attachment page for any Media returned as a search result. Many themes do not have useful templates for Media and very often it makes sense to link directly to the file itself instead.
This snippet will customize your search results template to link directly to Media files instead of an Attachment page.
All hooks should be added to your custom SearchWP Customizations Plugin.
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 | |
// Link directly to Media files instead of Attachment pages in search results | |
// @link https://searchwp.com/documentation/knowledge-base/link-file-pdf/ | |
function my_search_media_direct_link( $permalink, $post = null ) { | |
if ( | |
( | |
is_search() | |
|| doing_action( 'wp_ajax_searchwp_live_search' ) | |
|| doing_action( 'wp_ajax_nopriv_searchwp_live_search' ) | |
|| isset( $_REQUEST['swps'] ) | |
) | |
&& 'attachment' === get_post_type( $post ) | |
) { | |
$permalink = wp_get_attachment_url( $post ); | |
} | |
return esc_url( $permalink ); | |
} | |
add_filter( 'the_permalink', 'my_search_media_direct_link', 99, 2 ); | |
add_filter( 'attachment_link', 'my_search_media_direct_link', 99, 2 ); |