この記事は最後に更新してから1年以上経過しています。

ダッシュボードの「概要」にカスタム投稿タイプ件数を表示する

説明

管理者向けページが刷新したWordPress 3.8。そのダッシュボードページにはサイトの状況を示す「概要(At a Glance)」ウィジェットがある。この中には「投稿」や「固定ページ」の投稿件数が表示されており、同じようにカスタム投稿タイプの投稿件数を表示できないか調べてみた。

ダッシュボードの各ウィジェットは、/wp-admin/includes/dashboard.phpで定義されており、「概要(At a Glance)」ウィジェットの拡張ポイントを見てみると、'dashboard_glance_items'フィルターが用意されていた。

テーマのfunctions.phpに追加したコードは次の通り。

add_filter( 'dashboard_glance_items', 'mytheme_dashboard_glance_items' );
function mytheme_dashboard_glance_items( $elements ) {
	foreach ( array( 'food', 'drink' ) as $post_type ) {
		$num_posts = wp_count_posts( $post_type );
		if ( $num_posts && $num_posts->publish ) {
			$text = number_format_i18n( $num_posts->publish ).'件の投稿';
			$elements[] = sprintf( '<a href="edit.php?post_type=%1$s" class="%1$s-count">%2$s</a>', $post_type, $text );
		}
	}
	return $elements;
}

このフィルター関数は、パラメータ$elementsにリスト表示の内容(文字列)を追加し、それを返り値としている。青字の'food'と'drink'がカスタム投稿タイプ名であり、こちらは適宜変更してほしい。

追加したカスタム投稿タイプの件数は「○」アイコンで表示される。このアイコンは「Dashicons」と呼ばれており、3.8の管理者ページのいたるところで使用されている。アイコンを変更する場合は、独自のcssを追加すればいい。

add_action( 'admin_print_styles', 'mytheme_dashboard_print_styles' );
function mytheme_dashboard_print_styles() {
?>
<style>
#dashboard_right_now li a.food-count:before { content: '\f232'; }
#dashboard_right_now li a.drink-count:before { content: '\f233'; }
</style>
<?php
}

もちろんDashicons以外を指定することもできるが、まずはDashiconsで好みのアイコンを探すのがお手軽だろう。


最終更新 : 2013年12月17日 13:57


お勧め

wp_get_current_user(2019年6月21日 更新)

WP_User wp_get_current_user( )
現在のユーザ情報を取得する。

sanitize_locale_name(2023年5月22日 更新)

string sanitize_locale_name( $locale_name )
ロケール名をサニタイズする。

the_custom_logo(2018年5月27日 更新)

void the_custom_logo( [ int $blog_id = 0 ] )
カスタムロゴを表示する。

wp_unslash(2016年4月22日 更新)

mixed wp_unslash( mixed $value )
スラッシュでクォートされた文字列のクォート部分を取り除く。

wp_embed_defaults(2011年12月1日 更新)

array wp_embed_defaults( )
投稿記事中に埋め込む動画などのサイズを取得する。