Filter a query by a custom field

If you’re familiar with WP_Query, you’ve probably already used the meta_query parameter to filter results by one or more custom field values:

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

$args = [ 'post_type' => 'cars', 'post_status' => 'publish', 'meta_query' => [ [ 'key' => 'is_featured', 'compare' => 'EXISTS' ] ] ]; // Run the query $query = new WP_Query( $args );

Sort a query by a custom field

But did you know that you can also use meta_query for sorting the query, if you give the meta_query segment a named key? This feature was introduced in WordPress 4.2.

In the example below, we use featured as the key name. It can then be use within the orderby clause:

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

$args = [ 'post_type' => 'cars', 'post_status' => 'publish', 'meta_query' => [ 'featured' => [ 'key' => 'is_featured', 'compare' => 'EXISTS' ] ], 'orderby' => [ 'featured' => 'DESC' ] ]; // Run the query $query = new WP_Query( $args );

Sort a query by multiple custom fields

You can also sort by multiple custom fields, by using multiple meta_query keys. In the following example, we sort by featured and then by rating:

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

$args = [ 'post_type' => 'cars', 'post_status' => 'publish', 'meta_query' => [ 'featured' => [ 'key' => 'is_featured', 'compare' => 'EXISTS' ], 'rating' => [ 'key' => 'avg_rating', 'compare' => 'EXISTS', 'type' => 'numeric' ] ], 'orderby' => [ 'featured' => 'DESC', 'rating' => 'DESC' ] ]; // Run the query $query = new WP_Query( $args );

See also