You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义文章单页实现分类内文章序号/总篇数计数器

实现WordPress自定义文章类型分类内文章计数器短代码

需求说明

需要在WordPress自定义文章类型(slug为portfolio)的单篇文章页面,通过短代码显示格式为n/tot的计数器,其中:

  • n:文章在所属分类内的序号(分类内第一篇文章为1,第二篇为2,以此类推)
  • tot:该分类下已发布的文章总数

现有问题

已实现获取该自定义文章类型全局总发布数的短代码,但无法按分类统计,代码如下:

add_shortcode( 'tot_posts', 'number_factsheets' );
function number_factsheets () {
    $total = wp_count_posts('portfolio')->publish;
    $output = '<div class="count">';
    $output .= $total;
    $output .='</div>';
    return $output; 
}

解决方案:分类内计数器短代码

可以实现需求,以下是获取特定分类内自定义文章类型单篇文章序号与总篇数的可行代码:

add_shortcode('post-counter', 'get_current_post_num');
function get_current_post_num() {
    $url = $_SERVER['REQUEST_URI'];
    // 若$post对象已可用,可直接用get_the_ID()替代以下行
    $curr_post_id = url_to_postid( "https://sharkrayareas.org".$url );
    $taxonomy = 'portfolio_entries'; // 替换为你的自定义分类法slug

    $term_objs = get_the_terms( $curr_post_id, $taxonomy );
    $term_ids = [];
    foreach ($term_objs as $term_obj) {
        $term_ids[] = $term_obj->term_id; // 获取文章所属分类的ID
    }

    $args = array(
        'post_type' => 'portfolio',
        'post_status' => 'publish',
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy,
                'terms'    => $term_ids,
            ),
        ),      
        'order' => 'ASC', // 按文章发布顺序排序,可按需修改为DESC
        'posts_per_page' => -1 // 获取分类下所有已发布文章
    );
    $portfolio_posts = new WP_Query($args);
    
    $output = '';
    if ($portfolio_posts->have_posts()) {
        $total_posts = $portfolio_posts->found_posts;
        $num = 1;
     
        while ($portfolio_posts->have_posts()) : $portfolio_posts->the_post();
            $post_id = get_the_ID();

            if ($post_id === $curr_post_id) {
                $output = '<div class="count">'. $num . '/' . $total_posts .'</div>';
            } else {
                $num++;
            }
        endwhile;
        wp_reset_postdata(); // 重置查询,避免影响后续全局$post对象
    }
    return $output;
}

使用说明

  1. 短代码调用:在文章内容或模板中插入[post-counter]即可显示计数器
  2. 适配调整:
    • 若你的自定义分类法slug不是portfolio_entries,需修改代码中对应变量
    • 若在模板中使用且$post对象已初始化,可将$curr_post_id = url_to_postid(...)替换为$curr_post_id = get_the_ID(),提升效率
    • 可通过修改order参数调整排序规则(ASC为正序,DESC为倒序)

内容的提问来源于stack exchange,提问作者Elena Politi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 06:35:18