WordPress.org

Ready to get started?Download WordPress

Forums

How to sort custom post by custom date field (3 posts)

  1. dlm1897
    Member
    Posted 1 year ago #

    I have a custom post that uses template-event.php to display events that is currently being sorted by the posting date. I would like the events to be sorted by the event date instead. Using the Advanced Custom Fields plugin I created a custom date field called sortdate (yymmdd). I can echo the sort date for each event on my events page, but I cannot figure out how to sort the events based on this date. I have looked through numerous examples, but nothing seems to work for me. I've mostly been working with the following code that is found on the Event Page template:

    <?php
    $temp = $wp_query;
    $wp_query = null;
    $wp_query = new WP_Query();
    $wp_query->query('post_type=event' . '&paged=' . $paged . '');
    ?>
    
    <?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
    
    <?php
    $eventmonth = get_post_meta($post->ID, 'eventmonth', $single = true);
    $eventday = get_post_meta($post->ID, 'eventday', $single = true);
    $eventyear = get_post_meta($post->ID, 'eventyear', $single = true);
    $eventtime = get_post_meta($post->ID, 'eventtime', $single = true);
    $eventvenuename = get_post_meta($post->ID, 'eventvenuename', $single = true);
    $eventaddress = get_post_meta($post->ID, 'eventaddress', $single = true);
    $eventmaplink = get_post_meta($post->ID, 'eventmaplink', $single = true);
    $eventmap = get_post_meta($post->ID, 'eventmap', $single = true);
    $eventcost = get_post_meta($post->ID, 'eventcost', $single = true);
    ?>

    The following change is probably the closest I've gotten, as it will change the order from desc to asc, but I cannot get the $sortdate at that point in the code.

    $sortdate = get_field( 'sortdate' );
    $wp_query->query('post_type=event' . '&orderby=$sortdate&order=desc' . '&paged=' . $paged . '');

    Any ideas? Am I even going about this the right way? Thanks for the help, Derek

  2. Tara
    Member
    Posted 1 year ago #

  3. dlm1897
    Member
    Posted 1 year ago #

    Thanks for the response t-p. However, the following change seemed to have no effect on the list of events.

    <?php
    $temp = $wp_query;
    $wp_query = null;
    $wp_query = new WP_Query( array( 'post_type' => 'event', 'meta_key' => 'sortdate', 'order_by' => 'meta_value', 'order' => 'ASC' ) );
    $wp_query->query('post_type=event' . '&paged=' . $paged . '');
    ?>

    I'm really stuck on this one.

Topic Closed

This topic has been closed to new replies.

About this Topic