Showing posts with label WP_Query. Show all posts
Showing posts with label WP_Query. Show all posts

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.
read more...
 
Copyright © 2003 - 2014 Thom Allen Weblog • All Rights Reserved.