WordPress.org

Ready to get started?Download WordPress

Forums

Custom Fields (2 posts)

  1. MicoHono
    Member
    Posted 6 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
    Member
    Posted 6 years ago #

    Hi,

    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 = "
        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.

Topic Closed

This topic has been closed to new replies.

About this Topic