WordPressで記事数を取得する関数wp_count_posts()

SQL文でサイトの記事数を取得する方法もありますが、処理が重くなるので、WordPressで記事数を取得するときはwp_count_posts()関数を使います。

公開済みの投稿の記事数を取得

$count_posts = wp_count_posts();
$posts = $count_posts->publish;
echo '記事数は'.$posts.'件です';

公開済みの固定ページの記事数を取得

$count_pages = wp_count_posts('page');
$pages = $count_pages->publish;
echo '記事数は'.$pages.'件です';

公開済みの投稿と固定ページの記事数を取得

$count_pages = wp_count_posts('page');
$count_posts = wp_count_posts('post');
$pages = $count_pages->publish;
$posts = $count_posts->publish;
$count_all = $posts + $pages;
echo '記事数は'.$count_all.'件です';

公開済みのカスタム投稿タイプの記事数を取得

$count_custom = wp_count_posts('カスタム投稿タイプ名');
$custom_posts = $count_custom->publish;
echo '記事数は'.$custom_posts.'件です';

記事数が規定値を超えたら要素を表示する

上記の記事数取得を応用して、条件分岐も出来ます。

<?php 
    $count_posts = wp_count_posts();
    $posts = $count_posts->publish;
    //記事数が5より多かったら以下の要素を表示する
    if (5 < $posts):
?>
    <!-- 表示する要素 -->
<?php endif; ?>