我需要创建按年份分组的新闻文章标题的手风琴列表。到目前为止,手风琴面板的内容是正确的,每个面板都显示了该年的所有新闻。
问题是,根据年份的文章数,我多年来将获得多个面板。因此,例如2003年有三篇新闻文章,因此我得到了2003年的三个手风琴面板,每个面板都有该年的三篇相应的新闻文章。 2004年我得到一个手风琴面板,因为2004年只有一篇文章。2006年我有六个文章,所以我得到了六个面板,每个里面有六个文章。
我该怎么做才能只得到一个面板,里面的标题数量正确?
这是我的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 );
这是我的标记:
<?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>
以某种方式,我需要将第一个foreach限制为代表的每一年。我将不胜感激。
<?php $yearposts = array(); ?>
<?php foreach($newsposts as $year) : ?> <?php $postyear = $year->post_year; ?>
<?php if(!in_array($postyear, $yearposts)) { ?>
<li class="accordion-item" data-accordion-item>
<a href="#" class="accordion-title"><?php echo $postyear; array_push($yearposts,$postyear); ?></a>
<div class="accordion-content" data-tab-content>
<ul class="accordlist">
<?php foreach($newsposts as $post) : ?>
<?php // Continue unless years match
if ( $post->post_year != $year->post_year ) continue; ?>
<li><a class="newstitle" href="<?php the_permalink($post->post_id); ?>"><?php echo $post->post_title; ?></a></li>
<?php endforeach; //$posts ?>
</ul>
</div>
</li>
<?php } // end in_array conditional ?>
<?php endforeach; //$year ?>
</ul>
如显示的帖子所述,
基本上,我们只是使用一个附加数组来存储打印的值。每次看到新值时,我们都将其打印并添加到数组中。
我的版本被分解成包围手风琴格式所需的元素。无论如何,希望这对其他人有帮助。我需要不同问题的答案才能找到解决方案。现在也许有人会在这个地方找到所有东西。
欢呼声