特定の投稿タイプの記事総数を出力するショートコード

ワードプレス関数ファイルカスタム投稿タイプショートコード

キャッチ文「業界最大級の掲載数 ○○○ 件!」みたいなヤツ。

実際の掲載数を出力するショートコードです。

functions.php

//投稿タイプごとの公開済み記事数を出力する
//0
function count_posts( $atts, $content = null ) {
	if( !empty( $atts['post_type'] ) ){
		$post_type = $atts['post_type'];
	}else{
		$post_type = 'post';
	}
	$count_total_posts = wp_count_posts( $post_type );
	$count_published_posts = $count_total_posts->publish;
	return number_format( $count_published_posts );
}
add_shortcode( 'count_posts', 'count_posts');

指定例

「count_posts」

投稿タイプを指定しない場合は、公開済み「標準投稿」の件数を出力します。

「count_posts post_type=”facility”」

投稿タイプ「facility」の公開済み件数を出力します。


現在こんなエラーメッセージが出ているはずですが、

Warning: Undefined property: stdClass::$publish in /home/pico-cre/www/p3-guide/wp/wp-content/themes/P3/function/functions-shortcode.php on line 843

存在しない投稿タイプを指定するとこんな感じになります。

エラー処理も出来ますが、このショートコードを使うのは開発者、管理者あたり。

ならばエラーが出ないと困るはずなのでママとしてあります。