Ordering WP Posts by Custom Meta Key
Asked Answered
C

2

8

I created a WordPress custom post type to be able to create events, select the event's date, and display the date on the frontend.

I added a new meta_key in the postmeta of WP's database to store the event's date in a UNIX timestamp.

I've had no trouble creating a new WP query to output my events on my site but I am trying to figure out how to organize the events by their UNIX timestamp in the database, not by the date that WordPress created the events.

I can't seem to wrap my head around the thing.. any advice?

Considering answered 26/5, 2011 at 22:47 Comment(0)
V
19

I believe your query can have

'orderby' => 'meta_value_num',
'meta_key' => 'event_timestamp' //or whatever your meta_key is

you can read about it here: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

Vernacularism answered 26/5, 2011 at 23:27 Comment(6)
Wow! I overlooked those arguments.. Thanks!Considering
You're welcome. As of WP 3.1, there's also a meta_query argument, but it's complex.Vernacularism
Just wanted to add my two cents here to other people who might find this answer in future. The plugin "Post Type Reorder" could potentially interfere with this custom ordering, if used incorrectly (Auto). Took me a long time to figure this out.Quadrireme
Glad you found it useful. Where would we be without stackoverflow & google?Vernacularism
You saved my day!Incumber
Glad to hear it :)Vernacularism
R
2

Better use pre_get_posts:

function ta_modify_main_query($query) {
   if ($query->is_main_query()) {
       $query->set('orderby', 'meta_value_num');
       $query->set('meta_key', '_liked');
       $query->set('order', 'DESC');
   }
}

add_action( 'pre_get_posts', 'ta_modify_main_query' );
Respond answered 28/12, 2017 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.