Chetana Kestikar
Chetana Kestikar

Reputation: 570

Search functionality that also searches the keyword in custom fields of posts

The default search functionality in wp searches only the content of the posts/pages. But I have categories which have posts with custom fields (I have used advanced custom field plugin for it).I tried using many plugins as Relevanssi but still did not find a way to search in custom fields too. Maybe I am missing something. How to get the search results which include the custom fields too? Please help.

Upvotes: 1

Views: 1640

Answers (1)

Bindiya Patoliya
Bindiya Patoliya

Reputation: 2764

Try like this

function custom_search_where($where) {
// put the custom fields into an array
$customs = array('custom_field1', 'custom_field2', 'custom_field3');

foreach($customs as $custom) {
$query .= " OR (";
$query .= "(m.meta_key = '$custom')";
$query .= " AND (m.meta_value  LIKE '{$n}{$term}{$n}')";
    $query .= ")";
}

$where = " AND ({$query}) AND ($wpdb->posts.post_status = 'publish') ";
return($where);
}
add_filter('posts_where', 'custom_search_where');

Upvotes: 2

Related Questions