• 赤色のリンクは、まだ日本語Codexに存在しないページ・画像です。英語版と併せてご覧ください。(詳細

このWikiはいつでも誰でも編集できます

プラグインの作成

提供: WordPress Codex 日本語版
2008年10月11日 (土) 20:07時点におけるLily (トーク | 投稿記録)による版 (en から一部翻訳)

(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
移動先: 案内検索

はじめに

WordPress 1.2 より前では、WordPress の振舞いを変更したいと思ったとき、WordPress のソースコードを編集 (もしくは「いじる」) 必要がありました。ところが、現在の WordPress では、プラグインを使用して、コア部分に対して簡単に機能の変更や追加を行うことができます。プラグインという仕掛けの基本的なアイディアは、WordPress のコアを比較的単純に保ち、しかしながらプラグインによって入出力の内容を変更できるぐらい柔軟であるようにすることです。定義は以下の通りです:

WordPress プラグイン 
WordPress プラグインは PHP 言語で記述された、プログラムないし1つ以上の関数の集まりであり、WordPress ウェブログに (WordPress プラグイン・アプリケーション・インターフェース (API) で提供されるアクセスポイントやメソッドを使ってウェブログとシームレスに統合された) 特定の機能やサービスを追加します。

この記事は、WordPress の基本的な機能や PHP プログラミングに親しんでいることを前提としています。

資料

  • プラグイン・リソースでは、プラグイン開発者のための総合的な記事やリソースの一覧があります。外部サイトの記事や特別なトピックもあります。
  • プラグインについて学ぶ他のよい方法は、上手に書かれたプラグインの PHP ソースコードを眺めることです。例えば、Hello Dolly のように WordPress に同梱されているプラグインです。
  • プラグインを作成したら、プラグインの公開と宣伝を読んで、広く配布する方法を学んでください。

プラグインの作成

この節では、うまく構成された WordPress プラグインを作るために考慮すべき事項について、順序立てて説明していきます。

名前、ファイル、格納位置

プラグインの名前

The first task in creating a plugin is to think about what the plugin will do, and make a (hopefully unique) name for your plugin. Check out プラグイン and the other repositories it refers to, to verify that your name is unique; you might also do a Google search on your proposed name. Most plugin developers choose to use names that somewhat describe what the plugin does; for instance, a weather-related plugin would probably have the word "weather" in the name. The name can be multiple words.

プラグイン・ファイル

The next step is to create a PHP file with a name derived from your chosen plugin name. For instance, if your plugin will be called "Fabulous Functionality", you might call your PHP file fabfunc.php. Again, try to choose a unique name. People who install your plugin will be putting this PHP file into the WordPress plugin directory in their installation, wp-content/plugins/, so no two plugins they are using can have the same PHP file name.

Another option is to split your plugin into multiple files. Your plugin must have at least one PHP file; it could also contain JavaScript files, CSS files, image files, language files, etc. If there are multiple files, pick a unique name for a file directory and for the main PHP file, such as fabfunc and fabfunc.php in this example, put all your plugin's files into that directory, and tell your plugin users to install the whole directory under wp-content/plugins/.

In the rest of this article, "the plugin PHP file" refers to the main plugin PHP file, whether in wp-content/plugins/ or a sub-directory.

説明書

If you want to host your plugin on http://wordpress.org/extend/plugins/, you also need to create a readme.txt file in a standard format, and include it with your plugin. See http://wordpress.org/extend/plugins/about/readme.txt for a description of the format.

ウェブサイト

It is also very useful to create a web page to act as the home page for your plugin. This page should describe how to install the plugin, what it does, what versions of WordPress it is compatible with, what has changed from version to version of your plugin, and how to use the plugin.

ファイル・ヘッダー

Now it's time to put some information into your main plugin PHP file.

標準的なプラグイン情報

The top of your plugin's main PHP file must contain a standard plugin information header. This header lets WordPress recognize that your plugin exists, add it to the plugin management screen so it can be activated, load it, and run its functions; without the header, your plugin will never be activated and will never run. Here is the header format:

<?php
/*
Plugin Name: Name Of The Plugin
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
Description: A brief description of the plugin.
Version: The plugin's Version Number, e.g.: 1.0
Author: Name Of The Plugin Author
Author URI: http://URI_Of_The_Plugin_Author
*/
?>

The minimum information WordPress needs to recognize your plugin is the Plugin Name line. The rest of the information (if present) will be used to create the table of plugins on the plugin management screen. The order of the lines is not important.

ライセンス

It is customary to follow the standard header with information about licensing for the plugin. Most plugins use the GPL license used by WordPress or a license compatible with the GPL. To indicate a GPL license, include the following lines in your plugin:

<?php
/*  Copyright YEAR  PLUGIN_AUTHOR_NAME  (email : PLUGIN AUTHOR EMAIL)

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

    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
*/
?>

プラグインのプログラミング

Now, it's time to make your plugin actually do something. This section contains some general ideas about plugin development, and describes how to accomplish several tasks your plugin will need to do.

WordPress プラグイン・フック

Many plugins accomplish their goals by connecting to one or more WordPress plugin "hooks". The way plugin hooks work is that at various times while WordPress is running, WordPress checks to see if any plugins have registered functions to run at that time, and if so, the functions are run. These functions modify the default behavior of WordPress.

For instance, before WordPress adds the title of a post to browser output, it first checks to see if any plugin has registered a function for the "filter" hook called "the_title". If so, the title text is passed in turn through each registered function, and the final result is what is printed. So, if your plugin needs to add some information to the printed title, it can register a "the_title" filter function.

Another example is the "action" hook called "wp_footer". Just before the end of the HTML page WordPress is generating, it checks to see whether any plugins have registered functions for the "wp_footer" action hook, and runs them in turn.

You can learn more about how to register functions for both filter and action hooks, and what plugin hooks are available in WordPress, in プラグイン API. If you find a spot in the WordPress code where you'd like to have an action or filter, but WordPress doesn't have one, you can also suggest new hooks (suggestions will generally be taken); see バグの報告 to find out how.

テンプレートタグ

Another way for a plugin to add functionality to WordPress is by creating custom テンプレートタグ. Someone who wants to use your plugin can add these "tags" to their theme, in the sidebar, post content section, or wherever it is appropriate. For instance, a plugin that adds geographical tags to posts might define a template tag function called geotag_list_states() for the sidebar, which lists all the states posts are tagged with, with links to the state-based archive pages the plugin enables.

To define a custom template tag, simply write a PHP function and document it for plugin users on your plugin's home page and/or in the plugin's main PHP file. It's a good idea when documenting the function to give an example of exactly what needs to be added to the theme file to use the function, including the <?php and ?>.

データベースにデータを保存する方法

Most plugins will need to get some input from the site owner or blog users and save it between sessions, for use in its filter functions, action functions, and template functions. This information has to be saved in the WordPress database, in order to be persistent between sessions. There are two basic methods for saving plugin data in the database:

  1. Use the WordPress "option" mechanism (described below). This method is appropriate for storing relatively small amounts of relatively static, named pieces of data -- the type of data you'd expect the site owner to enter when first setting up the plugin, and rarely change thereafter.
  2. Create a new, custom database table. This method is appropriate for data associated with individual posts, pages, attachments, or comments -- the type of data that will grow as time goes on, and that doesn't have individual names. See プラグインでのテーブル作成 for information on how to do this.

WordPress オプション機構

See オプションページの作り方 for info on how to create a page that will automatically save your options for you.

WordPress has a mechanism for saving, updating, and retrieving individual, named pieces of data ("options") in the WordPress database. Option values can be strings, arrays, or PHP objects (they will be "serialized", or converted to a string, before storage, and unserialized when retrieved). Option names are strings, and they must be unique, so that they do not conflict with either WordPress or other plugins.

Here are the main functions your plugin can use to access WordPress options.

add_option($name, $value, $deprecated, $autoload);
Creates a new option; does nothing if option already exists.
$name
Required (string). Name of the option to be added.
$value
Optional (string), defaults to empty string. The option value to be stored.
$deprecated
Optional (string), no longer used by WordPress, You may pass an empty string or null to this argument if you wish to use the following $autoload parameter.
$autoload
Optional, defaults to 'yes' (enum: 'yes' or 'no'). If set to 'yes' the setting is automatically retrieved by the get_alloptions function.
get_option($option);
Retrieves an option value from the database.
$option
Required (string). Name of the option whose value you want returned. You can find a list of the default options that are installed with WordPress at the オプション・リファレンス.
update_option($option_name, $newvalue);
Updates or creates an option value in the database (note that add_option does not have to be called if you do not want to use the $description or $autoload parameters).
$option_name
Required (string). Name of the option to update.
$newvalue
Required. The new value for the option.

管理パネル

Assuming that your plugin has some options stored in the WordPress database (see section above), you will probably want it to have an administration panel that will enable your plugin users to view and edit option values. The methods for doing this are described in 管理メニューの追加.

プラグインの多言語化

Once you have the programming for your plugin done, another consideration (assuming you are planning on distributing your plugin) is internationalization. Internationalization is the process of setting up software so that it can be localized; localization is the process of translating text displayed by the software into different languages. WordPress is used all around the world, so it has internationalization and localization built into its structure, including localization of plugins. For background on WordPress's use of GNU gettext for localization, see WordPress の翻訳.

It is highly recommended that you internationalize your plugin, so that users from different countries can localize it. The process is fairly straightforward:

  • Choose a translation "text domain" name for your plugin. This is generally the same as your plugin file name (without the .php), and must be unique among plugins the user has installed.
  • Wherever your plugin uses literal text strings that will be displayed to the user (known as "messages"), wrap them in one of the two WordPress gettext functions. Note that in a plugin, you need to use the second argument, passing in the translation text domain name you chose, unlike in the core of WordPress (which leaves the $domain argument blank).
__($message, $domain) 
Translates $message using the current locale for $domain. Wrap text strings that you are going to use in calculations with this function.
_e($message, $domain) 
Translates $message using the current locale for $domain, and then prints it on the screen. Wrap text strings that you are directly printed with this function.
  • Create a POT file (translation catalog listing all the translatable messages) for your plugin, and distribute it with your plugin. Users will need to put their translated MO file in the same directory as your plugin's PHP file, and name it domain-ll_CC.mo, where ll_CC is the name of their locale. See WordPress の翻訳 for information on POT files, MO files, and locales.
  • Load the translations for the current locale and your text domain by calling load_plugin_textdomain before either of the gettext functions is called, but as late as possible in the session (because some multi-lingual plugins change the locale when they load). One possible implementation is to define an initialization function that is called at the top of all of your plugin functions. For instance, assuming your text domain is "fabfunc":
$fabfunc_domain = 'fabfunc';
$fabfunc_is_setup = 0;

function fabfunc_setup()
{
   global $fabfunc_domain, $fabfunc_is_setup;

   if($fabfunc_is_setup) {
      return;
   } 

   load_plugin_textdomain($fabfunc_domain, PLUGINDIR.'/'.dirname(plugin_basename(__FILE__)), dirname(plugin_basename(__FILE__)));
}

If your plugin isn't in its own subdirectory, you can leave out the second argument of load_plugin_textdomain.

If you are reading this section because you want to internationalize a Theme, you can basically follow the steps above, except:

  • The MO file goes into the theme directory (same place as style.css).
  • The MO file is named ll_CC.mo, where ll_CC is the name of the locale (i.e. the domain is NOT part of the file name).
  • To load the text domain, put the following (inside a PHP escape if necessary) in your theme's functions.php file:
load_theme_textdomain('your_domain');

プラグイン開発における推奨事項

This last section contains some random suggestions regarding plugin development.

  • The code of a plugin should follow the WordPress コード規約. Please consider the インラインドキュメント Standards as well.
  • All the functions in your plugin need to have unique names that are different from functions in the WordPress core, other plugins, and themes. For that reason, it is a good idea to use a unique function name prefix on all of your plugin's functions. Another possibility is to define your plugin functions inside a class (which also needs to have a unique name).
  • Do not hardcode the WordPress database table prefix (usually "wp_") into your plugins. Be sure to use the $wpdb->prefix variable instead.
  • Database reading is cheap, but writing is expensive. Databases are exceptionally good at fetching data and giving it to you, and these operations are (usually) lightning quick. Making changes to the database, though, is a more complex process, and computationally more expensive. As a result, try to minimize the amount of writing you do to the database. Get everything prepared in your code first, so that you can make only those write operations that you need.
  • SELECT only what you need. Even though databases fetch data blindingly fast, you should still try to reduce the load on the database by only selecting that data which you need to use. If you need to count the number of rows in a table don't SELECT * FROM, because all the data in all the rows will be pulled, wasting memory. Likewise, if you only need the post_id and the post_author in your plugin, then just SELECT those specific fields, to minimize database load. Remember: hundreds of other processes may be hitting the database at the same time. The database and server each have only so many resources to spread around amongst all those processes. Learning how to minimize your plugin's hit against the database will ensure that your plugin isn't the one that is blamed for abuse of resources.


外部リソース