Custom Fields (2 posts)

  1. MicoHono
    Posted 7 years ago #

    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 :)

  2. microkid
    Posted 7 years ago #


    I was confronted with the same problem a short while ago (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 = "
          $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
    $events = $wpdb->get_results( $query );

    Hope this saves you some time.

Topic Closed

This topic has been closed to new replies.

About this Topic