原理也比较简单,逆序获取今年所有文章,再获取当前文章下标即可。因为序号是不变的,所以获取后存在postmeta
中,可以减少资源消耗。另外提前对比文章时间,如果文章不是今年发布的直接返回。
下面的代码加到functions.php
中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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; } |
在循环内使用<?php echo fa_get_postIndex_bymeta();?>
即可。
如果是所有文章的序号则去掉date_query
即可。
本文转载自:大发残志
文章评论