Override WordPress Admin Panel Search

I’m trying to include post meta into the wordpress admin panel search. I did a reseach and I found out that I can use the “pre_get_posts” filter to set the post meta into the query. So I wrote the following code

 function custom_search_query( $query ) {
    if( is_admin() && $query->is_search) {
    $custom_fields = array(
        // put all the meta fields you want to search for here
        ["key" => "property-ref-code", "compare" => "LIKE"],
        ["key" => "property-status", "compare" => "="],
        ["key" => "price", "compare" => "="],
        ["key" => "rent-price", "compare" => "="],
        ["key" => "bedrooms", "compare" => "="],
    );

    $meta_query = $query->get('meta_query');

    if (empty($meta_query))
    {
        $meta_query = array();
    }
       $meta_query[] = array('relation' => 'OR');
        foreach($custom_fields as $cf) {

            $meta_query[] = array(
                'key' => $cf["key"],
                'value' => $query->query_vars['s'],
                'compare' => $cf["compare"],
            );
        }
        $query->set("meta_query", $meta_query);
   }

}
add_filter( "pre_get_posts", "custom_search_query");

That code now not only is not returning anything but it also breaks the wordpress search. What I mean. If you disable this code you can search by post title and It will return some results if exists. Then if you enable the code and search by post title is not returning anything.
Basically I want to search for properties by price, reference code etc which are postmeta fields that I did. Can anyone help me to extends the wordpress search, when I search for a property to search and the given meta_keys

Read More

Thank you

Related posts

Leave a Reply

2 comments

  1. The issue could be that if (empty($meta_query_args))always returns true as $meta_query_args are not defined. So the actual meta_queries from the search are removed.

  2. function extend_admin_search( $query ) {
    
        // Extend search for document post type
        $post_type = 'document';
        // Custom fields to search for
        $custom_fields = array(
            "_file_name",
        );
    
        if( ! is_admin() )
            return;
    
        if ( $query->query['post_type'] != $post_type )
            return;
    
        $search_term = $query->query_vars['s'];
    
        // Set to empty, otherwise it won't find anything
        $query->query_vars['s'] = '';
    
        if ( $search_term != '' ) {
            $meta_query = array( 'relation' => 'OR' );
    
            foreach( $custom_fields as $custom_field ) {
                array_push( $meta_query, array(
                    'key' => $custom_field,
                    'value' => $search_term,
                    'compare' => 'LIKE'
                ));
            }
    
            $query->set( 'meta_query', $meta_query );
        };
    }
    
    add_action( 'pre_get_posts', 'extend_admin_search' );