WPプラグイン開発入門 (6)アイコン

概要メタボックスにカスタム投稿タイプの件数が表示されてるようになりましたが、まだ気になる箇所がありますね。カスタム投稿タイプ名の前に表示されているアイコンが素っ気ありません。このアイコンを、WordPressに標準で組み込まれているアイコンに置き換えてみましょう。

dashiconとは

dashiconとは、WordPressに標準で組み込まれているアイコン群です。管理画面のメニューの前など、サイトの色々なところで使われています。

dashiconはPHPコードで使用するための名前、HTMLのクラス名で使用するための名前、CSSで使用するためのコードが準備されています。例えば、(ハートマーク)を例に取ると、

使用箇所コード
PHPdashicons-heart下記のregister_post_type()を参照
HTMLdashicons-heart<span class="dashicons dashicons-heart"></span>または
<span class="dashicons-before dashicons-heart"></span>
CSScontent: "\f487";p:before { content: "\f487"; }

dashiconを管理画面のサイドバーに追加する

早速、dashiconを追加してみましょう。まずは、管理画面の左側のサイドバーに表示されている「マイCPT-A」「マイCPT-B」の前に表示されているアイコンを変更してみます。それぞれ、(ベル)、(ハート)のアイコンにしてみましょう。

PHP
function drnp_add_my_custom_post_type() {
	$custom_post_types = array(
		'drnp-mycpt-a' => array(
			'type'      => 'drnp-mycpt-a',
			'name'      => 'マイCPT-A',
			'menu_icon' => 'dashicons-bell',
		),
		'drnp-mycpt-b' => array(
			'type'      => 'drnp-mycpt-b',
			'name'      => 'マイCPT-B',
			'menu_icon' => 'dashicons-heart',
		),
	);
	foreach ( $custom_post_types as $custom_post_type ) {
		register_post_type(
			$custom_post_type['type'],
			array(
				'labels'    => array(
					'name'          => $custom_post_type['name'],
					'singular_name' => $custom_post_type['name'],
				),
				'public'    => true,
				'menu_icon' => $custom_post_type['menu_icon'],
			)
		);

		if ( 0 === wp_count_posts( $custom_post_type['type'] )->publish ) {
			for ( $i = 1; $i <= 3; $i++ ) {
				wp_insert_post(
					array(
						'post_type'   => $custom_post_type['type'],
						'post_title'  => $custom_post_type['name'] . ' 記事 #' . $i,
						'post_status' => 'publish',
					)
				);
			}
		}
	}
}
dashboard-right-now-plus.php

register_post_type()関数の第2引数の配列にmenu_iconというキーを追加しました。値はdashicons-bellまたはdashicons-heartです。これで、サイドバーのアイコンが変わりました。

dashiconを概要メタボックスに追加する

では次に、概要メタボックスに表示されているアイコンを変更してみましょう。まず、このアイコンがどのように表示されているのか調べてみます。

#dashboard_right_now li a:before { content: "\f159"; }というCSSでdashiconが表示されています。ですから、.drnp-mycpt-a-count:before { content: "\f487" !important; }などのCSSを当てればアイコンが変わるはずです。

管理画面に独自のCSSを適用させる

テーマファイルにCSSを追加しても管理画面には反映されません。管理画面に独自のCSSを適用させるにはどうしたらよいでしょうか。「WordPress 管理画面 css」で検索すると、admin_print_stylesadmin_enqueue_scriptsが使えそうなことが分かります。どちらを使えばよいでしょうか。公式リファレンスを見ると、次のように書かれています。

do_action( ‘admin_print_styles’ )

admin_print_styles should not be used to enqueue styles or scripts on the admin pages. Use admin_enqueue_scripts instead.

admin_print_styles – Hook | Developer.WordPress.org

do_action( ‘admin_print_styles’ )

admin_print_stylesは管理画面でCSSやJSを読み込むために使うべきではありません。代わりにadmin_enqueue_scriptsを使ってください。

do_action( ‘admin_enqueue_scripts’, string $hook_suffix )

admin_enqueue_scripts is the proper hook to use when enqueuing scripts and styles that are meant to be used in the administration panel. Despite the name, it is used for enqueuing both scripts and styles.

admin_enqueue_scripts – Hook | Developer.WordPress.org

do_action( ‘admin_enqueue_scripts’, string $hook_suffix )

admin_enqueue_scriptsは、管理画面で使用するJavaScriptやCSSを読み込むときに使用する適切なフックです。名前とは異なりますが、JavaScriptとCSSのどちらを読み込むためにも使われます。

ということで、admin_enqueue_scriptsを使います。第2引数を使って管理画面の特定のページでのみ読み込ませることもできますが、今回は管理ページ全てで読み込まれるようにします。

PHP
function drnp_add_my_admin_style() {
	echo <<< 'EOT'
	<style>
		.drnp-mycpt-a-count:before { content: "\f16d" !important; }
		.drnp-mycpt-b-count:before { content: "\f487" !important; }
	</style>
	EOT;
}
add_action( 'admin_enqueue_scripts', 'drnp_add_my_admin_style' );
dashboard-right-now-plus.php

コードまとめ

PHP
<?php
/**
 * Dashboard Right Now Plus
 *
 * @package           DashboardRightNowPlus
 *
 * @wordpress-plugin
 * Plugin Name:       Dashboard Right Now Plus
 * Plugin URI:        https://gist.github.com/web83info/5747ac715e4544b408e91e2ec034ab05/
 * Description:       Add custom post type to "Right Now" meta box on WordPress dashboard
 * Version:           1.0.0
 * Requires at least: 6.4
 * Requires PHP:      7.2
 * Author:            web83info
 * Author URI:        https://labs.web83.info/
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 */

/**
 * カスタム投稿タイプdrnp-mycpt-a, drnp-mycpt-b を追加
 *
 * @return void
 */
function drnp_add_my_custom_post_type() {
	$custom_post_types = array(
		'drnp-mycpt-a' => array(
			'type'      => 'drnp-mycpt-a',
			'name'      => 'マイCPT-A',
			'menu_icon' => 'dashicons-bell',
		),
		'drnp-mycpt-b' => array(
			'type'      => 'drnp-mycpt-b',
			'name'      => 'マイCPT-B',
			'menu_icon' => 'dashicons-heart',
		),
	);
	foreach ( $custom_post_types as $custom_post_type ) {
		register_post_type(
			$custom_post_type['type'],
			array(
				'labels'    => array(
					'name'          => $custom_post_type['name'],
					'singular_name' => $custom_post_type['name'],
				),
				'public'    => true,
				'menu_icon' => $custom_post_type['menu_icon'],
			)
		);

		if ( 0 === wp_count_posts( $custom_post_type['type'] )->publish ) {
			for ( $i = 1; $i <= 3; $i++ ) {
				wp_insert_post(
					array(
						'post_type'   => $custom_post_type['type'],
						'post_title'  => $custom_post_type['name'] . ' 記事 #' . $i,
						'post_status' => 'publish',
					)
				);
			}
		}
	}
}
add_action( 'init', 'drnp_add_my_custom_post_type' );

/**
 * アンインストール時にカスタム投稿タイプdrnp-mycpt-a, drnp-mycpt-b の記事を削除
 *
 * @return void
 */
function drnp_uninstall_my_custom_post_type() {
	$args  = array(
		'post_type'   => array(
			'drnp-mycpt-a',
			'drnp-mycpt-b',
		),
		'numberposts' => -1,
	);
	$posts = get_posts( $args );

	foreach ( $posts as $post ) {
		wp_delete_post( $post->ID );
	}
}
register_uninstall_hook( __FILE__, 'drnp_uninstall_my_custom_post_type' );

/**
 * 概要メタボックスにカスタム投稿タイプの件数を表示
 *
 * @param array $elements 追加表示させる内容.
 * @return array 追加表示させる内容.
 */
function drnp_add_my_custom_post_type_to_right_now( $elements ) {
	$args       = array(
		'public'   => true,
		'_builtin' => false,
	);
	$post_types = get_post_types( $args, 'object', 'and' );
	foreach ( $post_types as $post_type ) {
		$num_posts = wp_count_posts( $post_type->name );
		if ( $num_posts && $num_posts->publish ) {
			$text = sprintf( '%s件の%s', number_format_i18n( $num_posts->publish ), $post_type->labels->name );
			if ( current_user_can( $post_type->cap->edit_posts ) ) {
				$elements[] = sprintf( '<a class="%1$s-count" href="edit.php?post_type=%1$s">%2$s</a>', esc_html( $post_type->name ), esc_html( $text ) );
			} else {
				$elements[] = sprintf( '<span class="%1$s-count">%2$s</span></li>', esc_html( $post_type->name ), esc_html( $text ) );
			}
		}
	}
	return $elements;
}
add_filter( 'dashboard_glance_items', 'drnp_add_my_custom_post_type_to_right_now' );

/**
 * 管理画面でのみ読み込むCSS
 *
 * @return void
 */
function drnp_add_my_admin_style() {
	echo <<< 'EOT'
	<style>
		.drnp-mycpt-a-count:before { content: "\f16d" !important; }
		.drnp-mycpt-b-count:before { content: "\f487" !important; }
	</style>
	EOT;
}
add_action( 'admin_enqueue_scripts', 'drnp_add_my_admin_style' );
dashboard-right-now-plus.php
Expand

関連サイト

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です