Adaptive Web

A web development blog

Sorting WordPress posts using multiple meta keys

Today we are going to learn about sorting WordPress posts using multiple meta keys. The method uses WP_Query and can be used in page templates, shortcodes functions, custom plugin scripts and a variety of other ways.

Occasionally it may be necessary to custom order posts using multiple meta keys. This can be achieved using the meta_query parameter of the WP_Query object.

Below I will show you how to order a custom post type called member, inside a page template, using 2 meta keys; board_position and current_employer. The example also shows you how to sort the results using both meta values.

$args = array(
  'post_type' => 'member',
  'meta_query' => array(
    'relation' => 'AND',
    'board_position_query' => array(
      'key' => 'board_position',
    ) ,
    'current_employer_query' => array(
      'key' => 'current_employer',
    ) ,
  ) ,
  'orderby' => array(
    'board_position_query' => 'ASC',
    'current_employer_query' => 'ASC',
  ) ,
$member_posts = new WP_Query( $args );

By using the meta_query parameter we can pass an array of arrays containing the meta keys we want to sort our posts with. The key index of each nested array matches the meta_key stored in the wp_postmeta database table.

If you are using this query in a page template and want to make use of the loop, the functions have_posts() and the_post() must be made methods of the $member_post object, as shown below.

while( $member_posts->have_posts() ) : $member_posts->the_post();
  // loop code goes here...

As you can see, sorting WordPress posts using multiple meta keys is a breeze thanks to WordPress.