oliwa
12/5/2018 - 7:58 AM

Wordpress Query for Events with Start- and End-Date

Wordpress Query for Events with Start- and End-Date

<?php // based on https://support.advancedcustomfields.com/forums/topic/how-do-i-filter-and-sort-event-posts-with-start-and-end-date/
  $query_args = array(
    //'paged' => 1,
    'post_type' => 'termine',
    'post_status' => 'publish',
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    'posts_per_page' => -1,
    'meta_key' => 'event_start_date',
    'meta_query' => array(
      'relation' => 'OR',
      // start date is coming or equal
      array(
        'key' => 'event_start_date',
        'value' => date('Ymd', strtotime('now')),
        'type' => 'numeric',
        'compare' => '>=',
      ),
      // end date is coming or equal
      array(
        'key' => 'event_end_date',
        'value' => date('Ymd', strtotime('now')),
        'type' => 'numeric',
        'compare' => '>=',
      ),
    ),
  );
  $my_query = new WP_Query($query_args);
?>

<?php if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); ?>

  <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
  <p class="datespan">
    <?php 
      $startdateformatstring = "D, d. M Y"; 
      $unixtimestamp = strtotime(get_field('event_start_date'));
    ?> 
    <span><?php echo date_i18n($startdateformatstring, $unixtimestamp); ?></span> um <span><?php the_field('event_start_time'); ?> Uhr</span>

    <?php
      $thisstartdate = get_field('event_start_date');
      $thisenddate = get_field('event_end_date');

      if ($thisenddate > $thisstartdate) :
        $dateformatstring = "D, d. M Y"; 
        $unixtimestamp = strtotime(get_field('event_end_date')); ?>
        bis <span><?php echo date_i18n($dateformatstring, $unixtimestamp); ?></span>
      <?php endif; ?>
  </p>
  <?php the_excerpt(); ?>
  <?php edit_post_link('edit','<p><span class="edit">','</span></p>'); ?>
  <hr class="divider" />

<?php endwhile; else : ?>