WordPress:Writing a Plugin

来自站长百科
Xxf3325讨论 | 贡献2008年4月28日 (一) 15:43的版本 (新页面: = Introduction = Prior to WordPress Version 1.2, if you wanted to modify the behavior of WordPress, you had to edit (or "hack") the WordPress source code. However, in more current versio...)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转至: 导航、​ 搜索

Introduction

Prior to WordPress Version 1.2, if you wanted to modify the behavior of WordPress, you had to edit (or "hack") the WordPress source code. However, in more current versions of WordPress, you can easily modify and add to the functionality of the core version of WordPress by using WordPress:Plugins. The basic idea of the plugin architecture is to keep the core of WordPress relatively simple, but flexible enough that nearly every aspect of its input and output can be modified by plugins. Here is a definition:

WordPress Plugin
A WordPress plugin is a program, or a set of one or more functions, written in the PHP scripting language, that adds a specific set of features or services to the WordPress weblog, which can be seamlessly integrated with the weblog using access points and methods provided by the WordPress Plugin Application Program Interface (API).

If you find yourself wishing that WordPress had some new or modified functionality, the first thing to do is to search various plugin repositories (which you can learn about in the WordPress:Plugins article), and see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your own plugins.

This article assumes you are already familiar with the basic functionality of WordPress, and PHP programming.

Resources

  • There is a comprehensive list of articles and resources for plugin developers, including external articles on writing plugins, and articles on special topics, in WordPress:Plugin Resources.
  • Another good way to learn about plugins is to look at the PHP source code for well-written plugins, such as Hello Dolly, a plugin that is distributed with WordPress.
  • Once you have written your plugin, read WordPress:Plugin Submission and Promotion to learn how to distribute it widely.

Creating a Plugin

This section of the article goes through the steps you need to follow, and things to consider when creating a well-structured WordPress plugin.

Names, Files, and Locations

Plugin Name

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 WordPress:Plugins 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.

Plugin Files

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.

Readme File

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.

Home Page

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.

File Headers

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

Standard Plugin Information

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.

License

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

Programming Your Plugin

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 Plugin Hooks

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 WordPress:Plugin 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 WordPress:Reporting Bugs to find out how.

Template Tags

Another way for a plugin to add functionality to WordPress is by creating custom WordPress:Template Tags. 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 ?>.

Saving Plugin Data to the Database

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 WordPress:Creating Tables with Plugins for information on how to do this.

WordPress Options Mechanism

See WordPress:Creating Options Pages 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, $description, $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.
$description
Optional (string), defaults to empty string. Description of the option, which is placed into the WordPress database in case someone browses the database to see what options are there.
$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 WordPress:Option Reference.
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.

Administration Panels

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 WordPress:Adding Administration Menus.

Internationalizing Your Plugin

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:Translating 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:Translating 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, 'wp-content/plugins');
}

If your plugin is in its own subdirectory, append that to 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');

Plugin Development Suggestions

This last section contains some random suggestions regarding plugin development.

  • The code of a plugin should follow the WordPress:WordPress Coding Standards. Please consider the WordPress:Inline Documentation 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.


External Resources