3

Each of my posts have a single custom field that is a string of a date (not the date of the post). Instead of my theme's current query, which orders by published date, I want to order by this custom field date. How can I change this query (the theme's query) to instead use my custom field (a string representation of a date)?

$timeline_query = new WP_Query(array( 
    'post_type' => 'post', 
    'orderby' => 'date', 
    'order' => 'DESC', 
    'posts_per_page' => -1 
));
4

The WP_Query page on the Codex has a section on Order & Orderby Parameters.

If you want to order the query by a custom field you should add 'orderby' => 'meta_value' AND you must also specify the custom field (called your_date_field in the above example) using the meta_key key in the query.

$timeline_query = new WP_Query(array( 
    'post_type' => 'post', 
    'orderby' => 'meta_value',
    'meta_key' => 'your_date_field' 
    'posts_per_page' => -1 
));
0

Just a note for those using the HTML5 type="date" field, the format is recorded in yyyy-mm-dd. I was using 'orderby' => 'meta_value-num' because I thought the date was numeric, and didn't get why the order was off. Then I saw this thread and used 'meta_value' instead and it worked!

NOTE I wanted to add this as a comment to RRikesh's answer, but can't comment because my account doesn't have a high enough reputation yet, so I had to add a new answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.