プラグインを作ろう

WordPressプラグインを自作してきます!

 

フォルダ構造

まずは、フォルダ構造を理解しましょう!

 

プラグインを作成するフォルダ

├ lib(メインファイルから分離したPHPファイル)

├ images(画像ファイル)

├ js(JavaScriptファイル)

├ style(CSS

└ languages(翻訳ファイル)

plugin.phpプラグインのメインファイル)

README.txt(説明等)

WordPressデバッグを有効にする

プラグインを開発するにあたり、まずはデバックを有効にします。

WordPressのルートディレクトリにある「wp-config.php」を開いて、コードを追加します。ローカルなら、C:\xampp\htdocs\wordpressにあります。

 

define('WP_DEBUG',true);

  

C:\xampp\htdocs\wordpress\wp-content\pluginsにmy-pluginというフォルダーを作成します。

まずはプラグイン情報を記述します

my-pluginフォルダーの下に、my-plugin.phpを作り以下を記述します。

 

<?php

/*

Plugin Name: My-Plugin

Plugin URI

Description: プラグイン作ります!

Version: 1.0.0

Author:oxy

Author URI: http://example.com

License: GPL2

*/

?>

<?php

/*  Copyright 作成年 プラグイン作者名 (email : プラグイン作者のメールアドレス)

 

    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

*/

?>

 

 

ちなみに、ライセンスのGPL2はWordPressと同じライセンスで、「誰でもプラグインを自由に使用でき、再配布や改変をした場合でも同じ条件を継承する」というものです。

 

作成年や、作成者、メールアドレスは適宜変更してください。 その下の英文は変更する必要はありません。

 

こんな感じでプラグインが追加されます

f:id:success-seed:20200414162043p:plain

有効化しておきましょう

 

独自のテンプレートタグを定義

まずは WordPress のデザインをカスタマイズする時に使える独自のタグを登録しましょう。 以下をmy-plugin.phpに 追加します。

 

function test_hello_world() {

     return "Hello World";

}

 

 

まずは単純にHello Worldを表示してみましょう。

テンプレート内で呼び出す時には、

 

echo test_hello_world();

 

とします。

例えば、デフォルトのテンプレートなら

C:\xampp\htdocs\wordpress\wp-content\themes\twentytwenty\singular.php

を編集してみましょう!

 

 

<main id="site-content" role="main">

 

の下に

 

<?php echo test_hello_world(); ?>

 

を入力するとこのようになります。

 

 

f:id:success-seed:20200414162101p:plain

 

このように新しくタグを追加できることがわかりました!