WordPress search filter by custom field

Does anyone know how to alter WordPress search to filter by query vars? The query vars are custom fields. For example, I have a custom post type “books” and I want users to be able to search based on the “book_author” custom field.

The url after I hit the search button looks like this:

Read More
?search_filter=book_author&s=tolkien&post_type=book

Any help would be greatly appreciated.

Related posts

Leave a Reply

1 comment

  1. You will want to do something like this within your PHP code on a search page.

    $args = array(
                  'post_type' => 'book',
                  'order' => 'asc',
                  'meta_query' => array(
                      array(
                          'key' => $_GET['search_filter'],
                          'value' => $_GET['s'],
                          'compare' => 'IN',
                          )
                      )
                  );
    $loop = new WP_Query( $args );
    

    of course you may want to look at securing the code against SQL injection etc etc but this gives you a starting point into creating a page which will do what you want.

    I would recommend reading more about WP_Query, especially the parts about order by and parameters.