wp_count_posts()を使って投稿の記事数を取得する
各投稿ステータスの投稿数を取得できるwp_count_posts()
を使って投稿の記事数を取得します。
テンプレートタグ/wp count posts – WordPress Codex 日本語版
使い方
初期値は投稿post
の投稿数を取得します。
$count_posts = wp_count_posts();
$post_number = $count_posts->publish;
echo $post_number; //投稿(post)の公開記事数を表示
カスタム投稿タイプでの使い方
第一引数にカスタム投稿タイプのスラッグを指定。
$count_posts = wp_count_posts('news'); // カスタム投稿タイプのスラッグを指定
$post_number = $count_posts->publish;
echo $post_number;
固定ページでの使い方
第一引数にpage
を指定。
$count_posts = wp_count_posts('page');
$post_number = $count_posts->publish;
echo $post_number;
公開済みの投稿数を表示する
$count_posts = wp_count_posts();
$post_number = $count_posts->publish;
echo $post_number;
下書きの投稿数を表示する
$count_posts = wp_count_posts();
$post_number = $count_posts->draft;
echo $post_number;
非公開の投稿数を表示する
$count_posts = wp_count_posts();
$post_number = $count_posts->private;
echo $post_number;
ゴミ箱にある投稿数を表示する
$count_posts = wp_count_posts();
$post_number = $count_posts->trash;
echo $post_number;
投稿数が1件以上の時に要素を表示する
<?php
$count_posts = wp_count_posts();
$post_number = $count_posts->publish;
if($post_number > 0){
echo '記事数:'.$post_number;
}
?>
投稿がない時に要素を表示する
<?php
$count_posts = wp_count_posts();
$post_number = $count_posts->publish;
if($post_number == 0){
echo '投稿はありません';
}
?>