I need to create an accordion list of news article titles grouped by year. So far the contents of the accordion panels are correct with each panel showing all of the news posts for that year.
The problem is that I'm getting multiple panels for years based on the number of articles for the year. So for example year 2003 has three news articles, so I'm getting three accordion panels for 2003, each with the three corresponding news articles for that year. For 2004 I get one accordion panel because there's only one article for 2004. 2006 has six articles so I get six panels each with the six articles inside.
What do I need to do to get only one panel with the correct number of titles inside?
Here's my SQL:
$newsposts = $wpdb->get_results("
SELECT YEAR(wp_posts.post_date) AS post_year, wp_posts.post_title, wp_posts.ID AS post_id
FROM wp_posts LEFT JOIN wp_term_relationships ON
(wp_posts.ID = wp_term_relationships.object_id)
WHERE wp_term_relationships.term_taxonomy_id = 3
AND wp_posts.post_status = 'publish'
ORDER BY post_date
", OBJECT );
Here's my markup:
<?php foreach($newsposts as $year) : ?> <?php //print_r($year); ?>
<li class="accordion-item" data-accordion-item>
<a href="#" class="accordion-title"><?php echo $year->post_year; ?></a>
<div class="accordion-content" data-tab-content>
<?php foreach($newsposts as $post) : ?> <?php //print_r($post); ?>
<?php // Continue unless years match
if ( $post->post_year != $year->post_year ) continue; ?>
<a href="<?php the_permalink($post->post_id); ?>"><?php echo $post->post_title; ?></a><br/>
<?php endforeach; //$posts ?>
</div>
</li>
<?php endforeach; //$year ?>
</ul>
Somehow I need to limit the first foreach to only one for each year represented. I would appreciate any help.