12 次查询 耗时 0.053 秒
本文共计896个字,0条留言,预计阅读时长3分钟
登录/注册
  • 首页
  • >
  • Notes
  • >
  • WordPress获取文章是年度的第几篇文章
  • WordPress获取文章是年度的第几篇文章

    作者:Misshylsay

    日期:2020年02月28日

    WordPress如何获取一篇文章属于发布年度的第几篇文章?有时候做周刊类的博客的时候需要用到这个,比如2020年第几期,如果手动写的话有时候会写错,今天给大家分享一种自动排序的方法。

    请将如下代码放入主题的function.php中:

    /*获取文章属于年度的第几篇文章*/
    function fa_get_postIndex_this_year( $postid = null ){
        global $post;
        $postid = $postid ? $postid : get_the_ID(); 
     
        $query_args = array(
            "posts_per_page" => -1,
            'order' => 'ASC',
            'date_query' => array(
                'year' => get_the_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_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;
    }

    调用方法:

    <span>[<?php echo the_time('Y')?>]第<?php echo fa_get_postIndex_bymeta();?>期 </span>	

    显示效果:[XXX年]第XX期。

    “WordPress获取文章是年度的第几篇文章”共有0条评论

    发表评论

    B em del U Link Code Quote