I am trying to create a function with post query and with following structure in output:
2021 January 1.Post Title 2.Post Title March 3.Post Title 2020 May 4.Post Title
Here is what I’ve done so far:
global $post;
$posts = get_posts( array(
'post_type' => 'history',
'orderby' => 'date'
) );
$_year_mon = '';
$_has_grp = false;
foreach ( $posts as $post ) {
setup_postdata( $post );
$time = strtotime( $post->post_date );
$year = date( 'Y', $time );
$mon = date( 'F', $time );
$year_mon = "$year-$mon";
if ( $year_mon !== $_year_mon ) {
// Close previous group, if any.
if ( $_has_grp ) {
echo '</div>';
echo '</div>';
}
$_has_grp = true;
echo '<div class="year">';
echo "<span>$year</span>";
echo '<div class="month">';
echo "<span>$mon</span>";
}
// Display post title.
if ( $title = get_the_title() ) {
echo "<div>$title</div>";
} else {
echo "<div>#{$post->ID}</div>";
}
$_year_mon = $year_mon;
}
if ( $_has_grp ) {
echo '</div>';
echo '</div>';
}
wp_reset_postdata();
The problem is that same year with multiple month is not grouped in one element..
Current output:
2021 January 1.Post Title 2.Post Title 2021 March 3.Post Title 2020 May 4.Post Title
2
Answers
Create an multidimensional array like this way and print it. You might get appropriate result.
As we talked on this question, when you use
get_posts
it will returnpost objects
. Eachpost object
contains the following properties/data:For example if you need,
title
,content
,author
,exerpt
of the post, then you could create a multi-dimensional array and usearray_push
function to create your custom array like so:For debugging/investigating the array, you could use this:
Now that you have your own custom array, then you could loop through it and output your data:
The above code will output the following result: