Modify admin query so that keyword is searched for in title AND custom field
-
How do I make it so that when an admin uses the ‘Search Posts’ form on the ‘All Posts’ admin page, the search word that he types in is used by WP to return posts where the ‘post_title’ field *OR* a custom field contains the search word.
I’m using the pre_get_posts action hook to modify the $query variable but WP seems only to be doing an AND search rather than the required OR search. Here is my code:
function my_pre_get_posts( $query ) { if ( is_admin() && $query->is_main_query() && $query->query['post_type'] === 'post' && isset($query->query['s']) ) { $search_word = $query->query['s']; //echo '<!-- keyword: ' . $search_word . ' -->'; /* * This only ANDs the post's title value and its my_field value. * (I need it to OR the two values.) */ //$query->query_vars['meta_key'] = 'my_field'; //$query->query_vars['meta_value'] = $search_word; //return /* * Same problem as above with this technique. */ //get the existing meta query $meta_query = $query->get('meta_query'); $meta_query_args = array( //Add our meta query to the original meta query 'relation' => 'OR', // Optional, defaults to "AND" array( 'key' => 'my_field', 'value' => $search_word, 'compare' => 'LIKE', ), /* //Including this sub-array makes no difference at all. It seems WP is using it's own code somewhere to search in post_title. array( 'key' => 'post_title', 'value' => $search_word, 'compare' => 'LIKE', ), */ ); //Set $meta_query if (is_array($meta_query)) { //Add to array $meta_query[] = $meta_query_args; } else { //Set/replace array $meta_query = $meta_query_args; } //set revised query $query->set('meta_query', $meta_query); //$query->set('meta_key', 'my_field'); //echo '<!--'; //print_r($query); //echo '-->'; } } add_action( 'pre_get_posts', 'my_pre_get_posts' );
I don’t think the problem is in my code. I think the problem is that WP is ANDing the meta_query with the post_title in its SQL, so how do I make it OR them instead?
Thanks in advance!
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
- The topic ‘Modify admin query so that keyword is searched for in title AND custom field’ is closed to new replies.