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; }
使用说明
- 短代码调用:在文章内容或模板中插入
[post-counter]即可显示计数器 - 适配调整:
- 若你的自定义分类法slug不是
portfolio_entries,需修改代码中对应变量 - 若在模板中使用且
$post对象已初始化,可将$curr_post_id = url_to_postid(...)替换为$curr_post_id = get_the_ID(),提升效率 - 可通过修改
order参数调整排序规则(ASC为正序,DESC为倒序)
- 若你的自定义分类法slug不是
内容的提问来源于stack exchange,提问作者Elena Politi
相关产品推荐
相关产品推荐

