Home    Articles

 

How to add meta query in wordpress admin search $query using 'pre_get_posts' hook

 

I've made this function to work as very custom admin area search functionality for a custom post type.

This custom post type had a several custom metas, so the task was to search by these custom metas. These custom metas were other custom post types so...obviously i had to rewrite entire query.

A very important line was $query->init(); that allowed me to reinitialize entire query string so i can fully customize it. 

I used pre_get_posts hook to get my function called at the right moment, this hook is called right before the DB interogation is made. A part of this query string is already created at this point so $query->init(); is quite mandatory if you need custom stuff.

Bellow is the code, you can debug it and do whatever you want. But remember, it is just an example, you have to change the code. This is my code for my task. Yours is different.

function custom_search_by_post_type( $query ) {
	global $wpdb;
    $query->init();
    $query->set('post_type','bpp_relation');
	$searchterm = (isset($_GET['s']))? $_GET['s']:'';
    #$query->query_vars['s'] = $searchterm;
	if ($searchterm != "" && isset($_GET['post_type']) && $_GET['post_type'] == 'bpp_relation') {
		$programs = array();
		$programResults = $wpdb->get_results( "SELECT ID FROM wp_posts WHERE post_type='bpp_program' AND post_title LIKE '%".$_GET['s']."%' LIMIT 50", OBJECT );
		foreach($programResults as $k=>$v) {
			$programs[] = $v->ID;
		}
		$companies = array();
		$companiesResults = $wpdb->get_results( "SELECT ID FROM wp_posts WHERE post_type='bpp_company' AND post_title LIKE '%".$_GET['s']."%' LIMIT 50", OBJECT );
		foreach($companiesResults as $k=>$v) {
			$companies[] = $v->ID;
		}
		
	    // we have to remove the "s" parameter from the query, because it will prevent the posts from being found
        $meta_query = array('relation' => 'OR');
        
		if(!empty($programs)) {
	        array_push($meta_query, array(
	            'key' => 'bonus_program',
	            'value' => $programs,
	            'compare' => 'IN'
	        ));
		}
		if(!empty($companies)) {
	        array_push($meta_query, array(
	            'key' => 'company',
	            'value' => $companies,
	            'compare' => 'IN'
	        ));
		}
        $query->set("meta_query", $meta_query);
        $query->set("post_status", array('draft','publish','private'));
       
    }
}
// add action to make custom query admin search in bpp_relation
add_filter( "pre_get_posts", "custom_search_by_post_type");

 

by