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.

Read More

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?

Related posts

Leave a Reply

2 comments

  1. 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' );