我几乎从零碎的工作中得到了我想要的东西,但我需要一些帮助来完成它。我尝试在页面模板(而不是单独的归档页面)中输出以下内容(对于自定义帖子类型):
<ul class="accordion">
<li>
<h3>2014</h3>
<div>
<p>12 September 2014</p>
<a href="the_permalink>"Post title 1</a>
</div>
<div>
<p>11 August 2014</p>
<a href="the_permalink>"Post title 2</a>
</div>
<div>
<p>10 May 2014</p>
<a href="the_permalink>"Post title 3</a>
</div>
</li>
<li>
<h3>2013</h3>
<div>
<p>20 June 2013</p>
<a href="the_permalink>"Post title 4</a>
</div>
<div>
<p>19 April 2013</p>
<a href="the_permalink>"Post title 5</a>
</div>
<div>
<p>18 January 2013</p>
<a href="the_permalink>"Post title 6</a>
</div>
</ul>
到目前为止,我得到的代码如下所示:
<?php
$years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = \'press-releases\' AND post_status = \'publish\' GROUP BY year DESC" );
foreach ( $years as $year ) {
$posts_this_year = $wpdb->get_results( "SELECT post_title FROM wp_posts WHERE post_type = \'press-releases\' AND post_status = \'publish\' AND YEAR(post_date) = \'" . $year->year . "\'" );
echo \'<ul class="accordion">\';
echo \'<li><h3>\' . $year->year . \'</h3>\';
foreach ( $posts_this_year as $post ) {
echo \'<div>\' . $post->post_title . \'</div>\';
}
echo \'</li>\';
echo \'</ul>\';
}
?>
这是我想要的基本内容。然而,我还需要将文章标题包装在永久链接中,并输出文章发布的日期。我相信这是一个简单的解决方案,但我不知道怎么做。有什么想法或者有没有更好的方法来实现我想要实现的目标?
感谢您的任何意见!
最合适的回答,由SO网友:TheDeadMedic 整理而成
您只需使用普通查询即可获取所有帖子(默认情况下,按日期降序排序),并在循环时将其分解:
<?php
$posts = new WP_Query(
array(
\'posts_per_page\' => -1,
\'post_type\' => \'press-releases\'
)
);
if ( $posts->have_posts() ) : ?>
<ul class="accordion"><?php
while ( $posts->have_posts() ) : $posts->the_post();
$year = get_the_time( \'Y\' );
if ( $posts->current_post === 0 )
printf( \'<li><h3>%s</h3>\', $year ); // First post, always open the <li>
elseif ( $last_year !== $year )
printf( \'</li><li><h3>%s</h3>\', $year ); // Unlike above, close the previous open <li>
?>
<div>
<p><?php the_time( \'j F Y\' ) ?></p>
<a href="<?php the_permalink() ?>"><?php the_title() ?></a>
</div>
<?php
if ( ( $posts->current_post + 1 ) === $posts->post_count )
echo \'</li>\'; // Always close the <li> at the end of the loop
$last_year = $year;
endwhile;
?></ul>
<?php endif ?>