Reputation: 773
I am working on a calendar script to output events that are grouped by month. Everything is working fine, except I can't figure out how to add a div wrapper around each month without some closing tag issues. Here is my loop code:
if ($posts) {
$month_titles = array();
$close = false;
foreach( $posts as $post ) {
setup_postdata( $post );
$month_title = date('F Y', strtotime(get_post_meta($post->ID,'_event_start_local', true)));
if(!in_array($month_title, $month_titles)) {
if($close) echo '</ul>';
echo '<h4>'.$month_title.'</h4>';
echo '<ul>';
$month_titles[] = $month_title;
$close = true;
}
echo '<li>'.get_the_title().'</li>';
}
if ($close) echo '</ul>';
}
Here is how this is current output:
<h4>Month Name 2018</ul>
<ul>
<li>Title of Event</li>
<li>Title of Event</li>
</ul>
I would like for it to be like this:
<div>
<h4>Month Name 2018</h4>
<ul>
<li>Title of Event</li>
<li>Title of Event</li>
</ul>
</div>
I have tried a few different ways to add the div wrap and it either closes too early or too late. I need a fresh set of eyes on this as I have been messing with it too long!
Upvotes: 0
Views: 87
Reputation: 147166
It seems just changing these lines:
if($close) echo '</ul>';
echo '<h4>'.$month_title.'</h4>';
to
if($close) echo '</ul></div>';
echo '<div><h4>'.$month_title.'</h4>';
should do what you want. Note you have to change the if on $close
in both places in your code)
Upvotes: 1
Reputation: 6953
This logic should work for what you want:
// preset some vars
$oldMonth = null;
$firstItem = true;
foreach($posts as $post) {
setup_postdata($post);
$month_title = date('F Y', strtotime(get_post_meta($post->ID,'_event_start_local', true)));
// check if we have a new month coming up:
if($oldMonth != $month_title) {
// when it's the first one ever, just open the div
if($firstItem) {
echo "<div>";
$firstItem = false; //..and remember that the following aren't the first
} else { // else close the previous ones and open a new one
echo "</ul></div><div>";
}
// show the new month and open the list
echo '<h4>'.$month_title.'</h4>';
echo '<ul>';
}
echo '<li>'.get_the_title().'</li>';
$oldMonth = $month_title; // remember the last month
}
// at the end close the last ul and last div
echo '</ul></div>';
Upvotes: 1