Read our latest blog posts, learn something new, find answers, and stay up to date.

Using meta_query With WordPress 3.1+

With WordPress 3.1 – we now have the ability to use “meta_query” to show posts associated with a certain custom field. I recently used this in order to create an events listing widget for a client. I needed to query posts in the “Events” category and that had a time stamp defined (which happened to be the start date of the event). The client wanted to show only current/future events (today or later) and wanted to show them in order by the closest event date to the furthest away.

Getting the general query together was a snap – but the orderby did not work unless I had the meta_key defined (this is documented but was overlooked initially).


$now = time();
$args = array(
	'category_name' => 'Events',
	'meta_query' => array(
			'key' => 'sdac_event_time_stamp',
			'value' => $now,
			'compare' => '>=',
			'type' => 'NUMERIC'
	'meta_key' => 'sdac_event_time_stamp',
	'order' => 'ASC',
	'orderby' => 'meta_value_num'
$events_query = new WP_Query( $args); 

If you take a look at the query itself – the trick was to capture the time now ($now) and then use the compare within the meta_query. Overall – this sort of query makes working with custom fields a lot easier. If you have not checked it out yet – take a look.

Function Reference/WP Query