miguel.nz

How to exclude images from your search keeping other files

November 4, 2015   |   1 minute read.

I was looking to be able to display PDF and other types of documents under my search page in WordPress and I couldn’t find an easy way to filter this with my $query variable. So I wrote the following code.

1- Get Images attachments ID’s in an array

function get_images(){
		
		$arr 	= array();
		$args 	= array(
			'post_type' 		=> 'attachment',
			'posts_per_page'	=> -1
		);


		$the_query = new WP_Query($args);
		if($the_query->have_posts()):
			while($the_query->have_posts()): $the_query->the_post();
				global $post;
				if( strpos($post->post_mime_type, 'image') !== false )
					array_push( $arr , $post->ID );
			endwhile;
		endif;

		wp_reset_query();

		return $arr;

	}

2- Exclude Images ID from the query

add_filter('pre_get_posts',function($query){

	if($query->is_search):
		$query->set('post__not_in', get_images() );
	endif;

});

Cons: You have to perform a WP_Query before performing the search_query so it is not the most optimal solution
Pros: Does the work.