Title: Custom Fields
Last modified: August 19, 2016

---

# Custom Fields

 *  [micohono](https://wordpress.org/support/users/micohono/)
 * (@micohono)
 * [18 years, 6 months ago](https://wordpress.org/support/topic/custom-fields-5-2/)
 * I have created a Custom Field for my posts, now is it possible to make the post
   order sort by that custom field? or what?
 * The key is Event Date
 * I want posts to sort by Event date, and I want the closest even to show up on
   top.
    Once that event has passed it goes into archive.
 * Thanks for any help 🙂

Viewing 1 replies (of 1 total)

 *  [microkid](https://wordpress.org/support/users/microkid/)
 * (@microkid)
 * [18 years, 5 months ago](https://wordpress.org/support/topic/custom-fields-5-2/#post-668417)
 * Hi,
 * I was confronted with the same problem [a short while ago](http://wordpress.org/support/topic/146404)(
   working on an events plugin too). Unfortunately there’s no built in way to do
   this, so you have to formulate a query yourself and use $wpdb->query() to get
   the list of posts.
 * Here’s the query I wrote to get all events before today. You should be able to
   grab what you need from this, particularly the JOINs.
 *     ```
       $today = mktime();
   
       $query = "
           SELECT
             $wpdb->posts.ID AS ID,
             $wpdb->posts.post_title AS title,
             $wpdb->posts.guid AS guid
           FROM $wpdb->posts
             LEFT JOIN $wpdb->postmeta
               ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
           WHERE $wpdb->postmeta.meta_key = 'enddate'
             AND $wpdb->postmeta.meta_value >= $today
             AND $wpdb->posts.post_status = 'publish'
             AND $wpdb->posts.post_type = 'post'
           ORDER BY $wpdb->posts.post_date
           DESC
           ";
   
       $events = $wpdb->get_results( $query );
       ```
   
 * Hope this saves you some time.

Viewing 1 replies (of 1 total)

The topic ‘Custom Fields’ is closed to new replies.

## Tags

 * [conditional](https://wordpress.org/support/topic-tag/conditional/)
 * [custom fields](https://wordpress.org/support/topic-tag/custom-fields/)
 * [query](https://wordpress.org/support/topic-tag/query/)

 * In: [Developing with WordPress](https://wordpress.org/support/forum/wp-advanced/)
 * 1 reply
 * 2 participants
 * Last reply from: [microkid](https://wordpress.org/support/users/microkid/)
 * Last activity: [18 years, 5 months ago](https://wordpress.org/support/topic/custom-fields-5-2/#post-668417)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
