按月份/日期分组帖子忽略年份

时间:2015-03-03 作者:KingStakh

需要按发布日期对自定义发布类型中的发布进行分组。

Example:
Jan (all posts posted in januar for all years 2010,2011 ... 2015)
1 (all posts posted in 1 januar for all years 2010,2011 ... 2015)
POST1
POST2
...
2 (all posts posted in 1 januar for all years 2010,2011 ... 2015)
POST1
POST2
...
Feb (all posts posted in januar for all years 2010,2011 ... 2015)
1 (all posts posted in 1 januar for all years 2010,2011 ... 2015)
POST1
POST2
...
现在我使用以下代码:

<table class="table table-striped">
<?php
$current_month = \'\';
$args = array(
\'post_type\' => \'dayinhistory\',
\'date_query\' => array(
\'month\' => \'1\',
),
\'order\' => \'ASC\'
);

query_posts( $args );

if ( have_posts() ) : while( have_posts() ): the_post();

$this_month = get_the_time( \'F\' );

if( $this_month != $current_month ){
$current_month = $this_month;
echo \'<tr><td colspan="4">\'; 
echo $current_month; 
echo \'</td></tr>\';
}
?>
<tr>
<td style="vertical-align:inherit;"><?php the_date(\'d.m.Y\', \'<span class="label label-info">\', \'</span>\'); ?></td>
<td style="vertical-align:inherit;"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></td>
<td style="vertical-align:inherit;"><span class="label label-default"><?php the_time(\'d M Y\'); ?></span></td>
</tr>
<?php endwhile;?>
<?php endif;?>
<?php wp_reset_query();?>
</table>
或者这个:

<?php
$the_query = new WP_Query( \'post_type=dayinhistory&monthnum=3\' );
echo \'<table class="table table-striped">\';
while ( $the_query->have_posts() ) {
$the_query->the_post(); 

$this_month = get_the_time( \'F\' );

if( $this_month != $current_month ){
$current_month = $this_month;
echo \'<tr><td colspan="4">\'; echo $current_month; echo \'</td></tr>\';
}
?>
<tr>
<td style="vertical-align:inherit;"><?php the_date(\'d.m.Y\', \'<span class="label label-info">\', \'</span>\'); ?></td>
<td style="vertical-align:inherit;"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></td>
<td style="vertical-align:inherit;"><span class="label label-default"><?php the_time(\'d M Y\'); ?></span></td>
</tr>                
<?php }
echo \'</table>\';
wp_reset_postdata();
?>
结果enter image description here

但帖子是按年排序的,而不是按日排序的。

1 个回复
SO网友:cybmeta

您可以使用month parameter of WP_Query 按月获取帖子。例如,要在3月发布所有帖子,忽略年份:

<?php
$the_query = new WP_Query( \'monthnum=3\' );
echo \'<ul>\';
while ( $the_query->have_posts() ) {
    $the_query->the_post();
    echo \'<li>\' . get_the_title() . \'</li>\';
}
echo \'</ul>\';
wp_reset_postdata();
?>

结束