Include postmeta in WordPress search

How can I tell the default WordPress search function to also look at the postmeta data?

For example, I have a postameta key called ‘item_number’ and if someone searches ‘113’, I’d like for it to check the key’s value as well as the post content.

Read More

Thanks!

Related posts

Leave a Reply

4 comments

  1. A quick and dirty way to include meta values inside your searching scope: you can hook into pre_get_posts and add a meta_query like this:

    Inside your functions.php:

    add_filter( 'pre_get_posts', 'so_9224493_adjust_search_query');
    function so_9224493_adjust_search_query( $query ) {
        if ( !is_admin() && $query->is_search ) { //the !is_admin() boolean ensures that this does not affect your dashboard
            $meta_query_arguments = array(
                array(
                    'key' => 'item_number', //this is where you would put your meta key
                    'value' => $query->query_vars['s'],
                    'compare' => 'LIKE',
                ),
            );
            $query->set('meta_query', $meta_query_arguments);
        };
    }
    

    The only problem with this route is that it will include the meta query so that your search query will only match posts that include the search term inside the Title/Content/Excerpt and the meta field, which might not be preferable for you.