I feel like I’m missing something really obvious, but I’ve looked and can’t figure this out. I have a CPT (request_form
) and I need to perform searches on meta queries (wp_postmeta) rather than the post title. The catch is I need to do this from the admin dashboard and my code isn’t working. I’ve done similar kinds of searches on the user side, but not the admin side before. I figured pre_get_posts
was the right hook to use, but I’m getting nowhere.
Two strange things I noticed.
meta_query
is present twice in the$query
object. Once at$query->query_vars['meta_query']
and once at$query->meta_query
.-
When I enable
SAVEQUERIES
inwp-config.php
and dump$wpdb->queries
, I don’t see my query being executed at all.function my_search($query) { if (!is_admin()) { return; } if ($query->query['post_type'] !== 'request_form') { return; } if (!$query->is_search) { return $query; } $search = $query->query_vars['s']; $meta_query = array( 'relation' => 'OR', array( 'key' => 'request_details', 'value' => $search, 'compare' => 'LIKE' ), array( 'key' => 'request_subject', 'value' => $search, 'compare' => 'LIKE' ) ); $query->set('meta_query', $meta_query); echo "<pre>"; var_dump($query); echo "</pre>"; return $query; } add_action('pre_get_posts', 'my_search');
If I query directly in the db using sequelpro with the follwing, I get back exactly the posts I expect (sorry, I know this isn’t exactly the same).
SELECT * FROM wp_postmeta WHERE meta_value LIKE "%basketball%"
Thanks for any help you can give!
1 Answer
You can install the Query Monitor plugin to see what actual query that is being executed when you perform a search.
I suspect the problem you are having is that you are not unsetting the initial query vars. You are adding the meta query, but you haven’t removed the s= parameter, which only searches for your keyword in the title, content and excerpt.
Below $query->set('meta_query', $meta_query);
, try adding either of these: $query->set('s', '');
to set ‘s’ to an empty string or $query->__unset('s');
to unset it.