Thursday, March 13, 2014

WordPress WP_Query Sorting On Meta Values

I recently needed to sort posts by values saved in a meta value field. The normal post object only has a reference to the meta values so I needed to figure out how to add a meta key, meta value, and direction to WP_Query. Here is what I did:

The meta key: event-details
The meta value: a:1:{i:0;a:7:{s:16:"event-start-date";s:10:"03-04-2014";s:14:"event-location";s:15:"Someplace, USA";s:10:"event-logo";s:4:"4301";s:10:"event-type";s:5:"Event";s:10:"event-link";s:36:"http://www.company.com/";s:10:"event-time";s:0:"";s:14:"event-end-date";s:10:"03-05-2014";}}

The value event-start-date is what I want to sort all the posts returned.

$query_args = array( 'post_type' => 'events',
'posts_per_page' => -1,
'order' => 'DESC',
'meta_key' => 'event-details',
'orderby' => 'meta_value event-start-date' );

$loop = new WP_Query( $query_args );


Now I have a post object that is sorted by the event-start-date. Took me a while to get the sorting right, but it works like a charm.
Share this article

2 comments:

  1. The one issue I've found with ordering by meta value is that if you are also using a meta_query that needs a relationship of OR in the same WP_Query it breaks your ordering because the field it uses for ordering is no longer required to be the same as the meta_key value in your query.

    ReplyDelete
  2. Thom AllenMarch 14, 2014

    Hm, yeah I can see that as a problem. I haven’t face that yet, but thanks for point it out.

    ReplyDelete

 
Copyright © 2003 - 2014 Thom Allen Weblog • All Rights Reserved.