Add custom field (value) to search result (without plugin)

I need to add custom field to wordpress search result.

This what i tried to do is used pre_get_posts filter, like this:

function search_filter( $query ) {

$key_fields = array ( ‘buty’ );
$value_field = $query->query_vars[‘s’];
$query->query_vars[‘s’] = ”;

if ( $value_field != ” ) {

$filter_query = array( ‘relation’ => ‘OR’ );

foreach ( $key_fields as $one_field ) {
array_push ( $filter_query , array (
‘key’ => $one_field,
‘value’ => $value_field,
‘compare’ => ‘LIKE’
) );
}
$query->set( ‘meta_query’ , $filter_query );

}

}
add_filter( ‘pre_get_posts’ , ‘search_filter’);

It works, but now search not working for post title and post content

So the question is: how to properly add custom field to WordPress search result without lose standard functionality?

Read more here:: Add custom field (value) to search result (without plugin)

Leave a Reply

Your email address will not be published. Required fields are marked *