可能很难描述:
我有一个custom-post-type
调用wr_event
还有一个自定义字段event_date
.
我有很多帖子,每个帖子都设置了event_date
. 非常直截了当。
我现在想做的就是列出events
已发布。所以我想要这个…
2012 | 2011 | 2010 | 2009 | 2008
我该怎么做?我曾想过遍历所有帖子并列出年份,但不知何故,我不知道如何做到这一点。
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $post;
$this_year = get_post_meta( $post->ID, \'event_date\', true );
$this_year = date(\'Y\', $this_year);
echo $this_year;
endwhile;
这样做的最佳和最简单的解决方案是什么?
UPDATE
rsort( $years ); // sorts the years array into reverse order
foreach ($years as $year) {
echo \'<a href="#\'.$year.\'" name="y\'.$year.\'" class="inactive">\'.$year.\'</a> <span class="sep">|</span> \';
}
最合适的回答,由SO网友:Simon Blackbourn 整理而成
像这样的东西应该可以完成这项工作:
global $post;
$years = array();
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$this_year = get_post_meta( $post->ID, \'event_date\', true );
if ( $this_year = date( \'Y\', $this_year ) ) {
if ( ! in_array( $this_year, $years ) ) {
$years[] = $this_year;
}
}
endwhile;
rsort( $years ); // sorts the years array into reverse order
echo implode( \' | \', $years );
要减少查询,可以将所有内容保存到
transient:
global $post;
$transient = \'all-post-years\';
$timeout = 14400; // 4 hours
if ( false === $out = get_transient( $transient ) ) {
$years = array();
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$this_year = get_post_meta( $post->ID, \'event_date\', true );
if ( $this_year = date( \'Y\', $this_year ) ) {
if ( ! in_array( $this_year, $years ) ) {
$years[] = $this_year;
}
}
endwhile;
rsort( $years ); // sorts the years array into reverse order
foreach ( $years as $year ) {
$out .= \'<a href="#\' . $year . \'" name="y\' . $year . \'" class="inactive">\' . $year . \'</a> <span class="sep">|</span> \';
}
if ( $out ) {
set_transient( $transient, $out, $timeout );
}
}
echo $out;