也许有更好的优化方法,但我会这样做:
使用WP\\u查询获取所有事件,并按自定义日期字段对其进行排序,循环遍历所有事件并创建一个新的多维数组。在此数组中,我们将按日期(月和年)对所有帖子进行分组。最后,循环遍历我们的新数组,以获取我们提取的日期和事件。代码如下:
<?php
// Edit these values
$custom_post_type = \'event\';
$custom_date_field = \'event_date\';
$order = \'ASC\'; // from the oldest to the newest
// query
$the_query = new WP_Query( [
\'post_type\' => $custom_post_type,
\'posts_per_page\' => - 1,
\'meta_key\' => $custom_date_field,
\'orderby\' => \'meta_value\',
\'order\' => $order,
] );
// We are creating new multidimensional array
$all_events = [];
while ( $the_query->have_posts() ) :
$the_query->the_post();
$date = strtotime( get_post_meta( get_the_ID(), $custom_date_field, true ) );
$month_year = date( "F Y", $date );
$all_events[ $month_year ][] = $the_query->post;
endwhile;
wp_reset_query();
// And to print this:
foreach ( $all_events as $month_year => $events ) : ?>
<h3><?php echo $month_year ?></h3>
<ul>
<?php
/** @var \\WP_Post $event */
foreach ( $events as $event ) : ?>
<li><?php
// post title
echo $event->post_title;
// any custom field
the_field( \'acf_custom_field\', $event->ID );
?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
你可以在第二秒内随心所欲
foreach
环根据需要进行编辑。