How can i get all post from my custom post type with each month ?
Here is how i'm doing it now, but it's only showing all titles.
<?php $news = new WP_Query( array( 'post_type' => 'notice', 'posts_per_page' => 999, 'order' => 'ASC' ) ); ?>
<?php while ( $news->have_posts() ) : $news->the_post(); ?>
<div class="testi-archive-list">
<a href="<?php the_permalink()?>"/> <h1><?php the_title()?></h1></a>
<p><?php the_field('sub_title_noticias')?></p>
</div>
<?php endwhile ?>
What i want is something like this:
January: Title 1 Title 2
February: Title 1 Title 2
And so on. Can anyone help ?
There doesn't seem to be a specific WordPress function to do this. wp_get_archives
comes close but no cigar. This code should do what you need, obviously you'll need to change it to suit the layout and style you're after.
<?php $news = new WP_Query( array( 'posts_per_page' => 999, 'order' => 'ASC' ) ); $previous_post_month = ''; ?>
<?php while ( $news->have_posts() ) : $news->the_post();
$this_post_month = date( "M",strtotime( the_date( '', '', '', false) ) );
if( $this_post_month != $previous_post_month)
echo '<h1>' . $this_post_month . '</h1>';
?>
<div class="testi-archive-list">
<a href="<?php the_permalink()?>"/> <h2><?php the_title(); ?></h2></a>
</div>
<?php $previous_post_month = $this_post_month;
endwhile ?>
To do this, all you need to do is to get the current month and year from the current post's post date, and then comparing that with the previous post's post date, month and then either displaying the date if the moths don't match or not display it if they match
To accomplish this, you need to:
Get the month from the current post's post date. To achieve this, use get_the_time( 'F' )
Get the previous post in the loop with $wp_query->posts['this will be current post -1 ']->post
.
Get and compare the months between the two posts
Display or do not display the date according to the comparison
<?php
$news = new WP_Query( array('post_type' => array( 'notice' ),'posts_per_page' => 999, 'order' => 'ASC' ));
if( $news->have_posts() ) {
while( $news->have_posts() ) {
$news->the_post();
$current_month = get_the_date('F');
if( $news->current_post === 0 ) {
the_date( 'F Y' );
}else{
$f = $news->current_post - 1;
$old_date = mysql2date( 'F', $news->posts[$f]->post_date );
if($current_month != $old_date) {
the_date( 'F Y' );
}
}
// output data for the post
?>
<div class="testi-archive-list">
<a href="<?php the_permalink(); ?>"/> <h2><?php the_title(); ?></h2></a>
<p><?php the_field('sub_title_noticias'); ?></p>
</div>
<?php
}//End while
}
?>