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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?