我有wp查询帖子。我按自定义字段“event\\u date”订购。(字段格式示例为2016年8月9日)。我正在从每个帖子中提取年份和月份,并将其添加为div类,但是我想按照父div为每个月包装所有帖子。在前端,我希望它像这样:
<div id="082016">
<div class="post 082016"><?php the_title();?></div>
<div class="post 082016"><?php the_title();?></div>
<div class="post 082016"><?php the_title();?></div>
</div>
<div id="092016">
<div class="post 092016"><?php the_title();?></div>
<div class="post 092016"><?php the_title();?></div>
</div>
<div id="102016">
<div class="post 102016"><?php the_title();?></div>
<div class="post 102016"><?php the_title();?></div>
<div class="post 102016"><?php the_title();?></div>
</div>
等等。是否可以将所有帖子打包到这样的父div?我该怎么做?
<?php
$args = array(
\'posts_per_page\' => -1,
\'post_type\' => \'event\',
\'meta_key\' => \'event_date\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'ASC\'
);
$wpquery = new WP_Query($args); ?>
<?php while( $wpquery->have_posts() ): $wpquery->the_post(); ?>
<?php
$date = get_field(\'event_date\');
$year = date(\'Y\',strtotime($date));
$month = date(\'m\',strtotime($date));
$day = date(\'d\',strtotime($date));
?>
<div class="<?php echo $month; echo $year;?>">
<h1><?php the_title();?></h1>
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
非常感谢您的帮助!
最合适的回答,由SO网友:Krzysztof Grabania 整理而成
这不能仅通过查询数据库来完成。首先,您必须遍历所有项目并创建按日期分组的帖子数组。
$args = array(
\'posts_per_page\' => -1,
\'post_type\' => \'event\',
\'meta_key\' => \'event_date\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'ASC\'
);
$wpquery = new WP_Query($args);
$posts = $wpquery->get_posts();
$ordered_posts = array();
foreach ($posts as $post) {
$meta_value = get_post_meta($post->ID, \'event_date\', true);
if (!$meta_value) {
continue;
}
$date = date(\'mY\', strtotime($meta_value));
$ordered_posts[$date][] = $post;
}
接下来,您必须遍历分组数组以显示所需的div:
foreach ($ordered_posts as $post_date => $posts) { ?>
<div id="<?php echo $post_date; ?>">
<?php foreach ($posts as $post): ?>
<div class="post <?php echo $post_date; ?>">
<?php echo $post->post_title; ?>
</div>
<?php endforeach; ?>
</div>
<? }