Searching custom fields in WordPress with meta_query
There have been quite a few incredibly useful features that were introduced in WordPress version 3.0, which came out over a year ago. However, perhaps my favorite didn’t come till half a year later when version 3.1 was released.
Previously, searching posts, pages or custom post types using custom field required a more-than-reasonable amount of work by directly querying the database with lots of nested SQL, which was fairly cumbersome. Fortunately, a new parameter was introduced into the query string arsenal streamlining this process.
If you look in the WordPress Codex for WP_Query, you’ll see a new(ish) parameter called ‘meta_query’, which does exactly that–queries meta data for a post. It can search singular fields, as well as multiple fields, and handles all your typical SQL operators, e.g., =, !=, LIKE, BETWEEN, and IN. As a bonus, meta_query also plays nicely with the search parameter, ‘s’, and works with custom post types and custom taxonomies.
There are two ways it can be used.
For singular queries:
$query = new WP_Query( array ( 'meta_key' => 'meta_value' ) );
For multiple queries:
$query = new WP_Query( array( 'post_type' =>; 'food', 'meta_query' => array( array( 'key' => 'color', 'value' => 'brown', 'compare' => 'NOT LIKE' ), array( 'key' => 'taste', 'value' => 'sweet' 'compare' => '=' ), ) );
Note that in that first example, the ‘compare’ key is left out in the second array. If nothing is set for ‘compare’, the default value of ‘=’ will be used.
Have A Project For Us?
Website design services & digital marketing tailored for user experience and
attracting the right traffic for you with support-that-matters!