Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering WP Posts by Custom Meta Key

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?

like image 225
cqde Avatar asked May 26 '11 22:05

cqde


People also ask

What is meta key in WP?

The metakey is used to retrieve the saved value from the database and display it. If you are a developer, chances are you already know about this WordPress function. https://codex.wordpress.org/Function_Reference/get_user_meta.

What is Meta_value_num?

'meta_value_num' – Order by numeric meta value (available with Version 2.8). Also note that a 'meta_key=keyname' must also be present in the query. This value allows for numerical sorting as noted above in 'meta_value'. 'post__in' – Preserve post ID order given in the post__in array (available with Version 3.5).


2 Answers

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

like image 177
yitwail Avatar answered Nov 22 '22 09:11

yitwail


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' );
like image 21
Magnus TechApple Avatar answered Nov 22 '22 11:11

Magnus TechApple