WordPressのプラグインを作ってみる。

ソースコードはこちら
https://github.com/kin29/wp-plugin-test/tree/master/admin-header-message

 

プラグインって「ハードル高そう」って思ってました。

まだよくわかってないですが、思ったほど難しくなかったです!

 

参考:

https://wpdocs.osdn.jp/Main_Page

https://hatsuka.info/wordpress/gpl

 

 

コメントを以下のように記載すると、プラグインと認識してくれます。

/**
 * Plugin Name: AdminMessage Maker
 * Plugin URI: https://github.com/kin29/wp-plugin-test/tree/master/admin-header-message
 * Description: You can set your like message in admin-page header.
 * Version: 1.0.0
 * Author: kin29
 * Author URI: https://kin29.info
 * License: GPL2
 */
/*  Copyright 2018 ki29 (email : kin29.com@gmail.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as
	published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

 

 

管理画面ではこんな感じ。

プラグイン詳細

 

 

「有効化」すると、こんななります。

左上に「hello,kin29!」と出てるのがプラグインのしわざです。

プラグインイメージ

 

\ソースの中身/

関数addTestは、WP_Admin_Barクラスの関数add_menuを使って、

idが my-menu のtitileが hello, kin29! のもの追加してます。(見たままw)

idに関しては、my-menuっていうのが既存であるのかと思ってましたが、

idの値はなんでもokでした。

titleの中身は表示させたい言葉はご自由に入れてください。

function addTest($x){
//$x='admin_bar_menu'
 $x->add_menu( array(
    'id' => 'my-menu',
    'title' => 'hello, kin29!'
  ) );
}
add_action('admin_bar_menu', 'addTest');

 

 

\add_action()何しとるん?/

グローバル変数の$wp_filterにキーとバリュー追加してるようですね。

上のコードを例にすると、

$wp_filter[‘admin_bar_menu’]に関数addTest()を追加したようです。

 

wp-include/plugin.phpより

function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
	return add_filter($tag, $function_to_add, $priority, $accepted_args);
}
function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
	global $wp_filter;
	if ( ! isset( $wp_filter[ $tag ] ) ) {
		$wp_filter[ $tag ] = new WP_Hook();
	}
	$wp_filter[ $tag ]->add_filter( $tag, $function_to_add, $priority, $accepted_args );
	return true;
}

 

 

 

\GPLとは?/

コメントアウトにある、License表記ですが、

部分はcodexでは以下のように書いています。

慣例として、標準プラグイン情報の次にプラグインのライセンス情報を書きます。多くのプラグインは WordPress と同じ GPL2、ないし GPL2 互換のライセンス (英文) を用いています。

多くのプラグインに沿って、GPL2と私は書いてます。

GPL=GNU General Public License。フリー(自由)ソフトウェアライセンスの事。WordPressやGithubなどはこのライセンスに属している。コピーライトの逆の「コピーレフト」であり、利用・改変・再配布ができる。GPLで配布したものが、再配布がされるとそれ自身もGPLとなり、自由の保証が広がっていき、良いコードがいろんな人の手で作られるのかなと思います。

 

 

\まとめ/

プラグインは意外と簡単にできる。(物によるが)

プラグイン情報(licenseとか)はちゃんと書こう!

 

投稿者:

kin29man

農学部卒の7年目エンジニアです👩‍💻 PHPとGASが好きです!

コメントを残す

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