この記事は最後に更新してから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


お勧め

count_users(2019年3月1日 更新)

array count_users( [ string $strategy = 'time' [, int $site_id = null ] ] )
役割別のユーザ数を取得する。

wp_embed_defaults(2011年12月1日 更新)

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

the_posts_navigation(2019年9月25日 更新)

void the_posts_navigation( [ array $args = array() ] )
アーカイブページ向けのナビゲーションを表示する。

show_admin_bar(2012年1月5日 更新)

void show_admin_bar( bool $show )
ツールバー(admin bar)を強制的に表示/非表示する。

wp_spam_comment(2013年9月6日 更新)

bool wp_spam_comment( $comment_id )
コメントをスパムにする。