[WordPress] プラグインを作ろう(2) 独自のカスタムフィールドを追加する

詳細仕様は決まっていないのですが、作りたいのは投稿画面に決まったフォーマットのデータを入力させるプラグイン。カスタムフィールドを使えば投稿画面に付加情報を入力することは可能ですが、毎回決まったフォーマットで入力させたい。

このような用途に使える良質なプラグインにCustom Field Templateがありますが、より厳格に入力フォーマットを限定し、さらに2次利用できればなぁと思っているので、自作してみることにします。

と、その前に便利なジェネレータを発見しましたのでご紹介します。

Fun With Plugins
ウィザード形式でプラグイン名など必要事項を入力していくだけで、WordPressのプラグインとしての骨格を作ってくれます。あとは関数などを追加していくだけ。

さて、上述のCustom Field Templateのソースを見ていくと、管理画面に任意の入力フォームを追加しているのはこの2行のようです。

require_once(ABSPATH . 'wp-admin/includes/template.php');
add_meta_box('cftdiv', __('Custom Field Template', 'custom-field-template'), array(&$this, 'insert_custom_field'), 'post', 'normal', 'core');

1行目は、2行目で使用しているadd_meta_box()関数を定義しているファイルなので読み込みは必須のようです。

2行目のadd_meta_box()が管理画面に任意の入力欄を追加しているみたい。Codexのadd_meta_boxのページをみるとそれぞれの引数の意味が分かります。

<?php add_meta_box('id', 'title', 'callback', 'page', 'context', 'priority'); ?>

idが管理画面に出現する入力欄のdivのid属性値。他とかぶらないようにすればよいでしょう。
titleが管理画面に出現する入力欄のタイトル。最初からあるものだと「抜粋」とか「カスタムフィールド」とか表示されている部分です。
callbackがコールバック関数名。ここで指定した関数が呼ばれると、なるほど。
pageはどの画面に追加するのかを指定。投稿ならpost、ページならpage、リンクならを入力。そのままですね。
contextpriorityはCodexを読んでもよく分かりませんが、無くても通るようなので無視。

と、管理画面に何かを追加できそうなことは分かったので、現時点でいったんプラグインの形にしてみました。

<?php
/*
Plugin Name: up_test_plugin
Plugin URI: [insert the plugin uri here]
Description: test
Author: u_p
Version: 0.1
Author URI: https://www.umbrellaprocess.com/
Generated At: www.wp-fun.co.uk;
*/

if (!class_exists('up_plugin_test')) {
class up_plugin_test	{

/**
* PHP 4 Compatible Constructor
*/
function up_plugin_test(){$this->__construct();}

/**
* PHP 5 Constructor
*/
function __construct(){
require_once(ABSPATH . 'wp-admin/includes/template.php');
add_meta_box('up_test_div', '追加フィールド', array($this, 'add_custom_field'), 'post');
}

function add_custom_field(){
echo '追加内容';
}
}
}

//instantiate the class
if (class_exists('up_plugin_test')) {
$up_plugin_test = new up_plugin_test();
}
?>

結果はこのとおり。

wpdemo1

管理画面に新しいパーツを追加できました!

とは言っても、まだ入力欄の形式になっていないのでinputタグなどを出力しないといけない。
セキュリティ上の必要性だと思いますが、Codexのadd_meta_boxのページではnonce値の指定方法が書かれています。これはそのまま使えば良さそうです。表示画面側では以下の隠しフィールドを入れておく(name・id属性値は適宜変更して良いでしょう)。

echo '<input type="hidden" name="myplugin_noncename" id="myplugin_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

入力した値は保存できないと意味がありません。保存するための関数でもnonce値が正しいかどうか判定する必要があるようですが、その部分もCodexから持ってくれば問題なさそうです。

if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}

if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
}

っつーことでとりあえず入力欄をひとつ追加してカスタムフィールドに保存するプラグインが出来ました!先は長い!

class up_plugin_test	{
/**
* PHP 4 Compatible Constructor
*/
function up_plugin_test(){$this->__construct();}

/**
* PHP 5 Constructor
*/
function __construct(){
require_once(ABSPATH . 'wp-admin/includes/template.php');
add_meta_box('up_test_div', '追加フィールド', array($this, 'add_custom_field'), 'post');
add_action('save_post', array($this, 'save_custom_field'));
}

function add_custom_field(){
global $post;

// Use nonce for verification
echo '<input type="hidden" name="up_test_noncename" id="up_test_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

// The actual fields for data entry
echo '<input type="text" name="up_test_field" value="' . get_post_meta($post->ID, 'up_test_field', true) . '" size="25" />';
}

function save_custom_field($post_id){
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['up_test_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}

if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
}

// OK, we're authenticated: we need to find and save the data
$mydata = $_POST['up_test_field'];

if (get_post_meta($post_id, 'up_test_field') == "")
add_post_meta($post_id, 'up_test_field', $mydata, true);
elseif($mydata !=get_post_meta($post_id, 'myplugin_new_field', true))
update_post_meta($post_id, 'up_test_field', $mydata);
elseif($mydata=="")
delete_post_meta($post_id, 'up_test_field', get_post_meta($post_id,'up_test_field',true));
}
}

参考サイト

Tutorial: Creating Custom Write Panels in WordPress

[WordPress] プラグインを作ろう(2) 独自のカスタムフィールドを追加する」への1件のフィードバック

コメントを残す

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