How to search CPT’s by meta query from the admin dashboard?

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 in wp-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!

Read more here:: How to search CPT’s by meta query from the admin dashboard?

Leave a Reply

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