3/3/2018 - 7:53 PM

Ordering (Sorting) Custom Queries

  $today = date('Ymd');
  $homepageEvents = new WP_Query(array(
    'posts_per_page' => -1,
    'post_type' => 'event',
    'meta_key' => 'event_date', // 'meta_key' is all of the extra or custom additional data associate with the post
    // - this just saying that we want to order things by the value of a piece meta data. 
    // - in this case a metaor custom field.
    // when set the 'orderby' => 'meta_value_num' you need to make sure another parameter name
    // 'meta_key' this is where you spe out specifically the name of the custom field that
    // you are interested in.
    // Note: 'meta_value' is how you tell wordpres that you want to order by a meta_key
    // 'orderby' => 'meta_value' :  is well suited for letters and words.
    // 'orderby' => 'meta_value_num' : is well suited for number
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    // 'meta_query' allowed you to give multiple conditions or thing to check for.
    'meta_query' => array(
        'key' => 'event_date', // custome field
        'compare' => '>=', // greater or equal to
        'value' => $today, // today date
        'type' => 'numeric' // define what type of format you want to use
  while($homepageEvents->have_posts()) {
    $homepageEvents->the_post(); ?>
    <div class="event-summary">
      <a class="event-summary__date t-center" href="#">
        <span class="event-summary__month"><?php
          $eventDate = new DateTime(get_field('event_date'));
          echo $eventDate->format('M')
        <span class="event-summary__day"><?php echo $eventDate->format('d') ?></span>  
      <div class="event-summary__content">
        <h5 class="event-summary__title headline headline--tiny"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
        <p><?php if (has_excerpt()) {
            echo get_the_excerpt();
          } else {
            echo wp_trim_words(get_the_content(), 18);
            } ?> <a href="<?php the_permalink(); ?>" class="nu gray">Learn more</a></p>
  <?php }

<p class="t-center no-margin"><a href="<?php echo get_post_type_archive_link('event') ?>" class="btn btn--blue">View All Events</a></p>