不知道怎么写标题,反正功能就是就是页面上显示这是今年的第几篇文章。原理也比较简单,逆序获取今年所有文章,再获取当前文章下标即可。因为序号是不变的,所以获取后存在postmeta中,可以减少资源消耗。另外提前对比文章时间,如果文章不是今年发布的直接返回。
下面的代码加到functions.php 中
<code>
function fa_get_postIndex_this_year( $postid = null ){
global $post;
$postid = $postid ? $postid : get_the_ID();
if ( get_the_date('Y') != date('Y') ) return;
$query_args = array(
"posts_per_page" => -1,
'order' => 'ASC',
'date_query' => array(
'year' => date('Y'),
)
);
$i = 0;
$the_query = new WP_Query($query_args);
while ($the_query->have_posts()) {
$the_query->the_post();
$i++;
if ( $postid == get_the_ID() ) return $i;
}
wp_reset_postdata();
}
function fa_get_postIndex_bymeta( $postid = null ){
global $post;
$postid = $postid ? $postid : get_the_ID();
if ( get_the_date('Y') != date('Y') ) return;
if ( get_post_meta($postid,'_index_this_year',true) ) return get_post_meta($postid,'_index_this_year',true);
$index = fa_get_postIndex_this_year( $postid );
add_post_meta($postid,'_index_this_year',$index);
return $index;
}
在循环内使用echo fa_get_postIndex_bymeta();即可,如果是所有文章的序号则去掉date_query即可。