I’m going round in circles with trying to include several custom fields in my search results. The custom fields are managed via ACF.

At first I want this for the admin. /wp-admin/edit.php?post_type=location.

I can’t see why this wont work. I have tried variations of it and different orders. I’ve also gone through the posts_search filter route with arrays but just can’t get this to work.

Any help appreciated.

add_filter('pre_get_posts', __NAMESPACE__ . '\\search_custom_fields');

function search_custom_fields($query)
{
if ($query->is_search && $query->is_main_query()) {
    // this works.
    echo "search_custom_fields:   " . $query->is_main_query() . " " . $query->is_search;
    echo "Setting meta_query in search_custom_fields. ";

    $search_word = get_query_var('s');

    $meta_query = array(
        'relation' => 'OR',
        array(
            'key'     => 'loc_refid',
            'value'   => get_search_query(),
            'compare' => 'LIKE',
        ), array(
            'key'     => 'location_postcode_preview',
            'value'   => get_search_query(),
            'compare' => 'LIKE',
        ),
    );

    // if i uncomment this no results appear?!
    // $query->set('meta_query', $meta_query);

    // these work have an affect on the results
    $query->set('orderby', 'date');  
    $query->set('order', 'ASC');

}

return $query;

}

print_r($query) gives me –

 [query_vars]=>
        [meta_query] => Array
                (
                    [key] => loc_refid
                    [value] => MN0068
                    [compare] => LIKE
                )

 [meta_query] =>  
 [date_query] => 
 [post_count] => 0
 ...

thanks in advance.

2 Answers
2

Have you tried it with add_action instead of add_filter ?

add_action('pre_get_posts', 'search_custom_fields');

Is public set to true for your post_type?

And for use on in admin, try:

if ( is_admin() && $query->is_main_query() ) {
    if ( $query->is_search ) {
       //etc.

Leave a Reply

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