自定义帖子类型:事件 - 显示未来30天的即将发生的事件

时间:2014-05-28 06:44:42

标签: php wordpress metadata custom-post-type wp-query

我需要显示接下来30天的即将发生的事件,并根据自定义日期字段对其进行排序。

以下是我现在正在使用的代码,但在隐藏旧事件和将事件限制为30天方面没有取得任何成功。

<?php 
    $todayDate = date('d F, Y');
    $futureDate = strtotime ( '+30 days' , strtotime ( $todayDate ) ) ;
    $futureDate = date ( 'd F, Y' , $futureDate );
    $eventsOpt = array(         
        'post_type' => 'ptype_events',
        'posts_per_page' => -1,
        'meta_key' => 'ptype_event_date',
        'meta_compare' => '>=',
        //'meta_value' => $todayDate,
        'orderby' => 'meta_value',
        'order' => 'ASC',
    );
    $events_query = new WP_Query($eventsOpt);
?>
<div class="eventsPosts">
  <?php while ($events_query->have_posts()) : $events_query->the_post(); 
            $date = get_post_meta($post->ID, 'ptype_event_date', true);
        ?>
  <div class="eventsPost clearfix">
    <h3 class="title">
      <?php the_title()?>
    </h3>
    Date: <?php echo $date ?> </div>
  <?php endwhile; ?>
  <?php wp_reset_query() ?>
</div>

注意:数据库中保存的日期采用此格式date('d F, Y'),我无法在保存时将其更改为时间戳,因为使用插件创建元字段。

请帮帮我。

此致

1 个答案:

答案 0 :(得分:1)

如果将日期存储为带格式的文本字符串,则需要将它们转换回日期,然后对其进行过滤和排序。我的猜测是,当您运行此代码时,6月3日的活动将在1月30日的日期之前显示。

以下是我如何做到这一点:

<?php 
//Get all the events
$eventsOpt = array(         
    'post_type' => 'ptype_events',
    'posts_per_page' => -1,
    'meta_key' => 'ptype_event_date',
    'orderby' => 'meta_value',
    'order' => 'ASC',
);
$events_query = new WP_Query($eventsOpt);

//Loop through them and filter out events before today and events in more than 1 month
$events_out = array();
while ($events_query->have_posts()) : $events_query->the_post(); 
   $ed = strtotime( get_post_meta($post->ID, 'ptype_event_date', true) );
   $temp = array();
   if ( $ed !== FALSE && $ed >= time() && $ed <= strtotime('+1 month') ) :
      $temp['date'] = date('d F, Y', $ed);
      $temp['title'] = get_the_title();
      $events_out[$ed] = $temp;
   endif;
endwhile;
wp_reset_query();

//Sort the events by date
ksort( $events_out );

//Write the output
$format = <<<EOF
<div class="eventsPost clearfix">
   <h3 class="title">
      %s
   </h3>
   Date: %s </div>
EOF;

foreach ($events_out as $event) {
   printf ($format, $event['title'], $event['date']);
} ?>