Extend search to include custom post meta

This snippet extends WordPress search function to include custom post meta.

Instructions
Add the following code to your functions.php

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
<?php
     function custom_search_query( $query ) {
    if ( !is_admin() &amp;&amp; $query-&gt;is_search ) {
        $query-&gt;set('meta_query', array(
            array(
                'key' => '__meta_key__',
                'value' => $query-&gt;query_vars['s'],
                'compare' => 'LIKE'
            )
        ));
         $query-&gt;set('post_type', '__your_post_type__'); // optional
    };
     }
     add_filter( 'pre_get_posts', 'dc_custom_search_query');
?>


function custom_search_query($query)
{
$custom_fields = array(
// put all the meta fields you want to search for here
"_post_title",
"text_english",
"text_deutsch"
);
$searchterm = $query->query_vars['s'];
// we have to remove the "s" parameter from the query, because it will prevent the posts from being found
$query->query_vars['s'] = "";
if ($searchterm != "")
{
$meta_query = array('relation' => 'OR');
foreach($custom_fields as $cf)
{
array_push($meta_query, array(
'key' => $cf,
'value' => $searchterm,
'compare' => 'LIKE'
));
}
$query->set("meta_query", $meta_query);
};
}
add_filter( "pre_get_posts", "custom_search_query");
add_action( "save_post", "add_title_custom_field");

function add_title_custom_field($postid)
{
// since we removed the "s" from the search query, we want to create a custom field for every post_title. I don't use post_content, if you also want to index this, you will have to add this also as meta field.
update_post_meta($postid, "_post_title", $_POST["post_title"]);
}

Reference

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s