If you’re looking how to filter your WordPress posts using WP_Query() by a specific custom meta field while sorting (orderby) another different custom field, here’s a nifty way to do it, utilizing WordPress’ meta_query class.

Filter & Sort

Using meta_query, we’re able to filter the posts down to only those that meet the criteria we set in a custom field while still allowing the posts themselves to by ordered by anything WordPress supports, or by another custom field of our choosing.

Our Solution

In the example below, the meta field we’d like to filter our posts by, using compare in our meta_query, is: filtered_meta_field. The posts must match the value provided in filtered_value on the filtered_meta_field field our compare operator, which in our case is: = (equal to).

The meta field we’d like to order our posts by in the example is: sort_meta_field, using meta_value_num (assuming the field value is a number) and ordered Ascending (low to high).

// WP_Query arguments
$args = array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
	'meta_query'     => array(
        	array(
            	'key'       => 'filtered_meta_field', // Filter by this post meta field
            	'value'     => 'filter_value', // Only posts with meta field above that equals this value
            	'compare'   => '=' // Only posts that have meta field values equal to your value
        	)
    	),
    	'orderby'        => 'meta_value_num', // Order posts numerically by...
    	'meta_key'       => 'sort_meta_field', // this meta field's value
    	'order'          => 'ASC</span>'
);

// The Query
$query = new WP_Query( $args );

For the orderby value above, there please reference the WordPress Codex to see your OrderBy options.

Leave a Reply

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

Continue Reading