<< Back to Blog

WordPress New Powerful “orderby” replaces need for “meta_query”

I was late to the party finding out about the new powerful “orderby” argument that came along with WordPress 4.0.

From the documentation:

orderby accepts a string, representing a column on which to sort:

$q = new WP_Query( array( 'orderby' => 'post_title' ) );
// or an alias
$q = new WP_Query( array( 'orderby' => 'title' ) );


This means that you can even “orderby” a custom field.¬†For example if you had a custom field utilizing Advanced Custom Field’s “Date Picker”, and named that field “event_date”:

$q = new WP_Query( array( 'orderby' => 'event_date' ) );

This would take whatever the contents of that custom field is and sort by it as expected. A welcome replacement to the convoluted method:

$q = new WP_Query( array( 'orderby' => 'meta_value_num', 'meta_key' => 'event_date', 'meta_query' => array(...etc ) );