この記事は最後に更新してから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_suspend_cache_addition(2023年6月8日 更新)

bool wp_suspend_cache_addition( [ bool $suspend = null ] )
キャッシュの追加を一時的に停止する。

wp_json_file_decode(2022年1月26日 更新)

mixed wp_json_file_decode( string $filename [ , array $options = array() ] )
JSONファイルをデコードする。

get_metadata_by_mid(2018年12月14日 更新)

object|bool get_metadata_by_mid( string $meta_type, int $meta_id )
IDを指定してメタデータを取得する。

human_time_diff(2019年11月18日 更新)

string human_time_diff( int $from [ , int $to = '' ] )
時間差を'5分'や'2日'のような感覚的な表現で取得する。

get_current_user_id(2013年9月18日 更新)

int get_current_user_id()
現在のログイン済みユーザーのIDを取得抽出する。