Wordpress Search in Post Meta

WordPress Search in Post Meta

Rate this article

Share this article
Share on facebook
Share on twitter
Share on linkedin
Share on email

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

 

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.

You may also like
Hold on!
We’ve gathered our industry knowledge and are sharing hacks, tips to increase e-commerce revenue. Contains best tips for scaling up your ecommerce business.