WPプラグイン開発入門 (8)オプション取得・更新

WordPressサイトの設定はテーマファイルやプラグインファイルではなく、データベース側に保存することができます。今回はwp_optionsテーブルに情報を保存する方法を試してみます。

Options API

ハンドブックには、Options APIに説明があります。説明されている関数は、以下の4つです。

  • add_option()
  • get_option()
  • update_option()
  • delete_option()

add_option()はオプション値を保存する関数です。add_option( 'キー', '値' );のようにしてwp_optionsテーブルに値を保存できます。保存した値はget_option( 'キー' );として取り出すことができます。update_option( 'キー', '値' );として既存の値を更新できます。delete_option( 'キー' );として値を削除できます。ここでの値は単純な文字列だけではなく、配列を指定することもできます。

add_option()はキーが既に存在する場合には値を上書きしません。値の初期値を設定する際に便利ですね。

オプション取得・更新

プラグインのコードを書き換えていきます。現在、概要メタボックスのアイコンはregister_post_type()で指定したアイコンが表示されますが、これを次回以降作成する編集画面で、任意のdashiconを指定できるようにします。概要メタボックスで表示するdashicon名をwp_optionsテーブルに保存するようにします。

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 ) {
		$dashicon_key = 'drnp_cpt_' . $custom_post_type['type'] . '_dashicon';
		add_option( $dashicon_key, $custom_post_type['menu_icon'] );
		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

dashiconアイコンをadd_option()で保存します。キー名はdrnp_cpt_カスタム投稿名_dashiconです。add_option()はすでにキーが存在するときに、値を上書きしません。それで、プラグインを初めて実行するときや、カスタム投稿タイプが追加された後などには実行されますが、2回目以降は何もしません。

概要メタボックス表示

今まではget_post_types()で取得したオブジェクトのプロパティーmenu_iconを表示していましたが、get_option()で取得したアイコンを表示します。ついでに、関数内で使う変数名を$post_typesから$custom_post_typesに変更しました。

PHP
function drnp_add_my_custom_post_type_to_right_now( $elements ) {
	$args              = array(
		'public'   => true,
		'_builtin' => false,
	);
	$custom_post_types = get_post_types( $args, 'object', 'and' );
	foreach ( $custom_post_types as $custom_post_type ) {
		$num_posts = wp_count_posts( $custom_post_type->name );
		if ( $num_posts && $num_posts->publish ) {
			$text     = sprintf( '%s件の%s', number_format_i18n( $num_posts->publish ), $custom_post_type->labels->name );
			$dashicon = get_option( 'drnp_cpt_' . $custom_post_type->name . '_dashicon' );

			if ( current_user_can( $custom_post_type->cap->edit_posts ) ) {
				$elements[] = sprintf(
					'<a class="drnp-cpt %1$s-count" href="edit.php?post_type=%1$s"><span class="drnp-cpt-icon dashicons %3$s"></span>%2$s</a>',
					esc_html( $custom_post_type->name ),
					esc_html( $text ),
					esc_html( $dashicon )
				);
			} else {
				$elements[] = sprintf(
					'<span class="drnp-cpt %1$s-count"><span class="drnp-cpt-icon dashicons %3$s"></span>%2$s</span></li>',
					esc_html( $custom_post_type->name ),
					esc_html( $text ),
					esc_html( $dashicon )
				);
			}
		}
	}
	return $elements;
}
PHP

プラグイン削除時の処理

プラグインを削除するときに、プラグインで使用したオプションをすべて削除することにします。立つ鳥跡を濁さず、ですね。プラグインで使用するオプションは、drnp_で始めることにしていますので、全オプションを取得し、foreachでループを回し、drnp_で始まるキーをdelete_optionで削除します。

PHP
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 );
	}

	$alloptions = wp_load_alloptions( true );
	foreach ( $alloptions as $option_key => $option_value ) {
		if ( false !== strpos( $option_key, 'drnp_' ) ) {
			delete_option( $option_key );
		}
	}
}
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 ) {
		$dashicon_key = 'drnp_cpt_' . $custom_post_type['type'] . '_dashicon';
		add_option( $dashicon_key, $custom_post_type['menu_icon'] );
		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,
	);
	$custom_post_types = get_post_types( $args, 'object', 'and' );
	foreach ( $custom_post_types as $custom_post_type ) {
		$num_posts = wp_count_posts( $custom_post_type->name );
		if ( $num_posts && $num_posts->publish ) {
			$text     = sprintf( '%s件の%s', number_format_i18n( $num_posts->publish ), $custom_post_type->labels->name );
			$dashicon = get_option( 'drnp_cpt_' . $custom_post_type->name . '_dashicon' );

			if ( current_user_can( $custom_post_type->cap->edit_posts ) ) {
				$elements[] = sprintf(
					'<a class="drnp-cpt %1$s-count" href="edit.php?post_type=%1$s"><span class="drnp-cpt-icon dashicons %3$s"></span>%2$s</a>',
					esc_html( $custom_post_type->name ),
					esc_html( $text ),
					esc_html( $dashicon )
				);
			} else {
				$elements[] = sprintf(
					'<span class="drnp-cpt %1$s-count"><span class="drnp-cpt-icon dashicons %3$s"></span>%2$s</span></li>',
					esc_html( $custom_post_type->name ),
					esc_html( $text ),
					esc_html( $dashicon )
				);
			}
		}
	}
	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>
		#dashboard_right_now .drnp-cpt:before {
			content: none !important;
		}
		#dashboard_right_now .drnp-cpt-icon {
			padding: 0 5px 0 0;
		}
	</style>
	EOT;
}
add_action( 'admin_enqueue_scripts', 'drnp_add_my_admin_style' );
dashboard-right-now-plus.php
Expand

関連サイト

コメントを残す

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