件数情報(全◯件中◯件〜◯件目)を表示

WordPress

とあるサイトでWordPressの投稿件数を表示する機会があったのでメモ。

function my_result_count() {
  global $wp_query;

  $paged = get_query_var( 'paged' ) - 1;
  $ppp   = get_query_var( 'posts_per_page' );
  $count = $total = $wp_query->post_count;
  $from  = 0;
  if ( 0 < $ppp ) {
    $total = $wp_query->found_posts;
    if ( 0 < $paged )
      $from  = $paged * $ppp;
  }
  printf(
    '<p>全%1$s件中 %2$s%3$s件目を表示</p>',
    $total,
    ( 1 < $count ? ($from + 1 . '〜') : '' ),
    ($from + $count )
  );
}

表示した箇所に以下を記入。

if ( have_posts() ) : 
  my_result_count();  // ここら辺で表示します
  while ( have_posts() ) :
    the_post();
    /* do stuff */
  endwhile;
else :
  /* Nothing Found */
endif;

 

こちらに記載されていたものをまんま使えました。

WordPress で「全◯件中◯件〜◯件目を表示」を表示する
検索結果や各種アーカイブなどの記事一覧でページネーションする場合によくある表示「全◯件中◯件〜◯件目を表示しています」の決定版をお届けします。件数取得のために改めて get_posts() 的なことをしないので WordPress に優しい...

ありがとうございます!

参考リンク

500 Internal Server Error
[WordPress] WP_Queryで投稿取得後に全件数を求める | きほんのき
WP_Queryでposts_per_pageで数を限定した取得を行った後に全件数を知るにはfound_postsプロパティを使います。
タイトルとURLをコピーしました