Wordpress Search in Post Meta

Wordpress Search in Post Meta

Rate this article
[ratemypost]
Share this article

Read this blog on Wordpress search in post meta for more information.

Are you looking for a way to extend the search to include custom post meta? While there’s probably a plugin for this, we have created a quick code snippet that you can use to extend the search to include custom post meta in WordPress.

Wordpress Search in Post Meta

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
 * Extend wp search to include custom post meta
 */
function custom_search_query( $query ) {
    if ( !is_admin() && $query->is_search ) {
        $query->set('meta_query', array(
            array(
                'key' => '__meta_key__',
                'value' => $query->query_vars['s'],
                'compare' => 'LIKE'
            )
        ));
         $query->set('post_type', '__your_post_type__'); // optional
    };
}
add_filter( 'pre_get_posts', 'dc_custom_search_query');

Sign Up for ExpertRec

 

Are you showing the right products, to the right shoppers, at the right time? Contact us to know more.
You may also like