在WordPress中获取文章序号的方法

在主题中的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

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容