A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Wordress: Using custom fields as key to sort queries with meta_query and meta_key

The example shows that I sort posts with custom field “Start Date”. I am using ‘meta_query’ to query the custom fields – you can find out more here.

$args['post_type'] = array('ur_post', 
$args['meta_key'] = 'Start Date';
$args['meta_query'] = array(
        'key' => 'Start Date',
        'value' => date('Ymd'),
        'compare' => '>=',
        'type' => 'date'
/*This will sort. Make sure there is no underscore. It's orderby NOT order_by.*/
$args['orderby'] = 'meta_value'; 
$args['order'] = 'asc';
$the_query = new WP_Query($args);
while ( $the_query->have_posts() ) {
    $start_date = get_post_custom_values('Start Date', $the_query->ID);
    if (date('Ymd',strtotime($start_date[0])) >= date('Ymd')) {     
        echo '<div class="event_date">';
        //display date here...
        echo '</div>';
        echo '<div class="event_post_time">';
        $start_time = get_post_custom_values('Start Time', $the_query->ID);
        echo $start_time[0];
        $end_time = get_post_custom_values('End Time', $the_query->ID);
        if ($end_time != NULL) {
            echo ' - '.$end_time[0];
        echo '</div>';
This entry was posted in General and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>