Exclude images (attachments) from search results

⚠️ Code snippets might not be compatible with the latest version of your theme. Always use a child theme to customize your theme, and test your code on a staging website before migrating to production.

So you’ve set up a really neat search on your Customizr website with the this snippet. It works fine. But when you look at the search results on your site, all you see is screens and screens of images where you were hoping to see your pages and posts.

Here are two ways to exclude image attachments from your search results.

 

Either using Customizr functionality

Add the following code to your functions.php:

// Exclude images from search results - Customizr
add_action('wp_loaded', 'exclude_images_from_search_results', 100);
function exclude_images_from_search_results(){
    if ( method_exists('TC_post_list', 'tc_include_attachments_in_search') )
        remove_filter( 'pre_get_posts', array(TC_post_list::$instance,'tc_include_attachments_in_search') );
}

 

Or using WordPress functionality

Add the following code to your functions.php:

// Exclude images from search results - WordPress
add_action( 'init', 'exclude_images_from_search_results' );
function exclude_images_from_search_results() {
	global $wp_post_types;

	$wp_post_types['attachment']->exclude_from_search = true;
}

 

Where to copy/paste this code? => in your functions.php file. We strongly recommend you create a child theme. Download a start-up child theme here.

Remember: you shouldn’t edit the theme’s functions.php.

Leave a comment

Your email address will not be published. Required fields are marked *

20 thoughts on “Exclude images (attachments) from search results”