WordPress显示今年的第几篇文章(获取文章序号)方法
原理也比较简单,逆序获取今年所有文章,再获取当前文章下标即可。因为序号是不变的,所以获取后存在postmeta中,可以减少资源消耗。另外提前对比文章时间,如果文章不是今年发布的直接返回。
下面的代码加到functions.php 中
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即可。
原文链接:https://www.qiquanji.com/post/7005.html
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
微信扫码关注
更新实时通知