この記事は最後に更新してから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_authenticate(2022年1月31日 更新)

WP_User | WP_Error wp_authenticate( string $username, string $password )
ユーザー認証を行う。

wp_send_json_success(2020年12月10日 更新)

void wp_send_json_success( [ mixed $response = null [ , int $status_code = null [ , int $options = 0 ] ] ] )
AJAXリクエストの成功レスポンスとしてJSON情報を返す。

wp_oembed_get(2014年11月16日 更新)

mixed wp_oembed_get( string $url [ , mixed $args = '' ] )
oEmbedに対応したページの埋め込み用コンテンツを取得する。

setup_postdata(2014年11月16日 更新)

bool setup_postdata( stdClass $post )
投稿記事に関連するグローバル変数を設定する。

the_permalink(2018年5月27日 更新)

void the_permalink( [ mixed $post = 0 ] )
現在の投稿データのパーマリンクを表示する。