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 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计