dongmeixian9665 2019-02-11 18:19
浏览 86
已采纳

WordPress的帖子数:X中的Y?

I'm working on a theme with CPT. In single-cpt.php, I want to show the post number out of the total posts.

I managed to show the total ok posts using :

   <?php $args = array(
    'post_type' => 'cpt_type',
    'post_status' => 'published',
    'numberposts' => -1
);
echo $num = count( get_posts( $args ) ); ?>

and it returns the total of posts for that CPT type. So, on each single cpt, I got the total number.

What I would like, is to have "post number" / "total posts". Example : 7/21, and when I go o the following post : 8/21 and so on...

So, how could I get each single post to have a "number"?

Thanks!

  • 写回答

1条回答 默认 最新

  • doulan4371 2019-02-11 18:53
    关注

    Paste this in functions.php:

    function get_total_number_of_posts( $post ) {
        $posts = get_posts( array(
            'post_type'      => $post->post_type,
            'posts_per_page' => -1
        ) );
    
        return count( $posts );
    }
    
    function get_current_post_index( $post ) {
        $posts = get_posts( array(
            'post_type'      => $post->post_type,
            'posts_per_page' => -1
        ) );
    
        $index = 0;
    
        foreach ( $posts as $p ) {
            $index++;
    
            if ( $p->ID === $post->ID ) {
                break;
            }
        }
    
        return $index;
    }
    

    and then in your single.php file:

    global $post;
    
    $total_posts  = get_total_number_of_posts( $post );
    $current_post = get_current_post_index( $post );
    
    echo "You are viewing {$current_post} out of {$total_posts}";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试