WordPress:Writing a Plugin

来自站长百科
Seadragon530讨论 | 贡献2008年5月11日 (日) 18:35的版本
跳转至: 导航、​ 搜索

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.

介绍

WordPress 1.2版本之前,如果你想要修改WordPress行为,你必须编辑(或者 "hack") WordPress 源代码。尽管如此,在更多的现行WordPress版本中 ,你可以通过使用插件很容易的修改添加核心功能。基本的插件结构的想法是保持WordPress核心相关内容的简洁,但是富有灵活性,足以使各个输入输出方面可以通过插件来修改。下面是定义:

WordPress 插件
WordPress 插件是一个程序,或者是一组或更多函数,由PHP脚本语言编写,添加某种特殊的功能或者服务到WordPress weblog,使用接入点和WordPress Plugin Application Program Interface (API) 提供的方法,可以与weblog很好的结合在一起。

如果你发现你希望WordPress能拥有一些新的或者改良的功能,第一件事就是搜索各种插件库(你可以从 插件文章中了解),然后看是否某人已经创建了这样的适合你的需要的插件。如果没有,本文将指导你如何创建你自己的插件的过程。

本文假设你已经熟悉基本的WordPress功能以及 PHP编程。

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.

资源

  • 有很多插件开发者的的全面的文章列表和资源,插件资源中包括有关编写插件的外部文章以及关于特比话题的文章。
  • 另外一个了解有关插件的好方法是看写的好的插件的PHP 源代码,如 Hello Dolly, 一个分布式插件。
  • 一旦你写了插件,阅读插件提交和宣传来学习如何让它更广泛的散布开来。

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.

创建插件

本部分进入你需要遵守的几个步骤,和一些考虑什么时候建立一个结构良好的 WordPress插件。

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.

名字,文件和位置

插件名字

创建插件的第一个任务是想出插件要做什么,然后起一个(希望是唯一的)名字。 查看插件 和其他的相关库,验证你的名字是唯一的;你也可以使用Google搜索。 多数插件开发者选择使用能描述插件功能的那个名字; 如,一个联系到天气的插件啃含有单词"weather"在名字中。名字可以是好几个词。

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.

插件文件

下一步是创建PHP文件,文件名由你选择的插件名衍生而来。如,如果你的插件叫做"Fabulous Functionality",你可以吧你的PHP文件起名为 fabfunc.php。试着取一个唯一的名字。人们安装你的插件的时候会把这个PHP文件放到WordPress插件目录中,wp-content/plugins/,所以没有两个不同的在使用的插件拥有相同的PHP文件名。

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.

另外一个操作是把你的插件分成几个文件,你的插件至少要有一个PHP 文件,它可以包含JavaScript文件,CSS文件,图片文件和语言文件等等。如果有几种文件选择了唯一的文件夹和主PHP文件名字,如fabfuncfabfunc.php,就把所有的插件文件放到这个目录下,然后告诉你的插件用户安装整个目录到wp-content/plugins/下。

在这个文章的其余部分,"插件PHP文件"引用了主插件PHP文件,可以在 wp-content/plugins/ 或者一个子目录下

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.

自述文件

如果你想在http://wordpress.org/extend/plugins/上建立一个插件主机,你还需要用标准格式创建readme.txt文件,把它放到你的插件中去。参见 http://wordpress.org/extend/plugins/about/readme.txt 获得这格式的描述.

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.

主页

创建一个网页来作为你的插件的主页也是非常有用的。这个页面可以描述如何安装插件,它可以做些什么,兼容WordPress 的哪个版本,版本更替的时候你的插件做出了哪些改动,如何使用插件等等。

File Headers

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

文件标题

现在开始在你的插件的主PHP文件中添加信息。

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.

标准插件信息

插件主PHP文件的顶部必须包含一个标准插件信息标题。这个标题让WordPress 识别你的插件存在,添加到插件管理界面以便激活,载入,运行; 没有标题,你的插件将不会被激活也不会运行,如下是标题格式:

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

WordPress需要用来识别你的插件的最小信息是Plugin Name这行,其他信息(如果出现的话) 将用来创建插件管理界面上的插件表格。这些行的顺序并不重要。

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

许可

根据带有许可信息这个标准标题是个惯例。多数插件使用WordPress 使用的GPL 许可,或者是一个 compatible with the GPL的许可。简要说明下GPL许可,在你的插件中添加如下几行:

<?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.

WordPress 插件 Hooks

很多插件通过连接一个或者多个的WordPress 插件 "hooks"来完成它们的目标。 插件hooks的工作方式是在WordPress运行的时候,在各个不同的时候,WordPress检查是否有插件在那时有注册过的函数在此刻运行,如果有的话,函数运行。三个函数更改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.

例如,在WordPress添加文章标题到浏览器输出的时候,首先检查是否有任何插件为"filter"hook注册了一个函数叫做"the_title"。如果有,标题文字会被每个注册函数按顺序传递,最终结果就是打印出来的结果。这样,如果你的插件需要添加一些信息到打印标题,它可以注册一个"the_title" filter函数.

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.

另一个例子是"action" hook,叫做"wp_footer"。在WordPress生成的HTML页面的底部,它检查看是否某个插件已经为 "wp_footer" action hook注册函数,然后依次运行。

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.

你可以了解更多关于如何为filter 和 action hooks注册函数,什么插件hooks在WordPress和在插件API中可用。如果你在WordPress代码中发现一个你想使用action或者filter的地方,但是WordPress没有,你可以建议使用新的hooks (建议通常都会被采纳); 如何建议参见提交错误

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 ?>.

模板标签

另外一种用插件添加WordPress功能的方法是通过建立自定义 模板标签。有人想使用你的插件添加这些 "标签"到他们的主题,边栏,文章目录或者其他任何合适的地方。例如,添加地理标签到文章中的插件,可以为边栏定义一个叫做geotag_list_states()的模板标签函数,列出所有的有关国家,并带有国家文章页面的链接。

想要定义一个模板标签,需要简单的写一个PHP 函数并为插件用户在插件主页或者是插件PHP主文件中写下资料说明。在给函数做资料说明时,给出一个具体需要加入什么到主题文件中以使用函数的例子是个不错的想法包括 <?php?>.

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.

保持插件数据到数据库

大多数插件需要从站长或者blog用户得到一些信息并保存在sessions中,为了在它的filter 函数, action 函数和模板函数中使用。这个信息必须保存在WordPress 数据库中,为了在sessions中可以持久稳定。有两种基本方法可以保存插件数据到数据库中:

  1. 使用WordPress "操作"机制(下有描述)。这个方法适合储存相关的小量静态的指定的数据 – 那种你希望在第一次设置插件时站长输入的,今后几乎不会更改的数据。
  2. 创建一个新的自定义的数据库表格。这种方法适合联合单独的文章,页面,附件或者评论的数据—一种随着时间而增加的,没有单独的名字的数据。参见 创建插件表格.

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.

WordPress 操作机制

参见创建操作页面 得到关于如何创建自动为你保存操作的页面的信息。

WordPress有一个保存,更新,重新得到个体, 制定的数据("操作")机制,在 WordPress 数据库中。操作值可以是字符串,数组或者是PHP对象(它们将被 "连载",或者在存储前转变为字符串,在重新得到个体时反连载)。操作名字是字符串,它们必须是唯一的,这样它们不会与其他 WordPress或者是插件起冲突。

这里是你的插件可以用来进入WordPress操作的主要函数。

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.

管理面板

假设你的插件有一些操作存储在WordPress数据库中 (参见上面的部分),你也许希望有一个管理面板,允许你的插件用户来查看和编辑操作。方法可以在 添加管理目录中找到。

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.

让你的插件国际化

一旦你插件的程序完成了,另一个需要考虑的是(假设你打算发布你的插件) 国际化. 国际化是建立软件的一个过程,这样它才可以本地化 ;本地化是翻译软件的显示文本为其他语言。WordPress是全世界使用的,所以它有国际化和本地化版本,包括本地化的插件。想要知道关于WordPress的 GNU gettext的本地化使用,参见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.

强力推荐你国际化你的插件,这样来自不同国家的用户,可以本地化插件,过程如下:

  • 给插件选择一个翻译"文本区域"名字。这通常和你的插件文件名字一样(除了 .php), 而且必须是用户安装过的插件中唯一的。
  • 不论在哪里插件使用的显示给用户的文本(即"消息"), 使用一个或者两个 WordPress gettext 函数把它们包围起来。注意在插件中,你需要使用第二种方法,你选择的翻译文本区域名字中的传递,不像WordPress核心(留下 $domain 这部分空白).
__($message, $domain)
使用现有本地$domain翻译 $message。换行你将要用来用这个函数计算的文字字符串。
_e($message, $domain)
使用现有本地$domain翻译 $message, 然后在屏幕上显示出来,换行你使用这个函数直接显示出的文本字符串。
  • 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.

  • 创建一个POT文件(翻译目录列出了所有的可以翻译的信息),随着你的插件分发出去。用户将需要把他们的翻译过的MO文件放在你的插件的PHP文件的同一目录下,命名为domain-ll_CC.mo,那里ll_CC是本地文件的名字。参见翻译WordPress以获得关于POT文件,MO文件和本地文件的信息。
  • 通过在调用gettext函数之前调用load_plugin_textdomain为现有本地文件和你的文本区域文件载入翻译,在session中越晚越好,(因为一些多语言插件载入时改变了本地文件)。一个可能的办法是定义一个初始化函数,在所有插件函数之前调用,如,假设你的文本区域是"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');

如果你阅读了这个部分因为你想要国际化一个主题,你大体上可以按照上面的步骤来,除非:

  • MO文件在主题目录中(与style.css同样的位置).
  • MO 文件命名为ll_CC.mo, ll_CC是本地文件名(这个域不是文件名字的一部分).
  • 想要载入文本域,加入如下代码(在某个PHP 溢出,如果需要的话) 到你的主题的functions.php文件:
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.

插件开发建议

最后一部分包括一些关于插件开发的建议。

  • 插件代码应该遵循 WordPress编码标准。请参照内嵌文档标准。
  • 所有的插件中的函数需要有唯一的名字,因为这个原因,在所有插件函数中使用唯一的函数名字前缀是个很好的主意。另一个可能性是在类中定义你的插件函数(也需要有唯一名字).
  • 不要吧WordPress数据库表格前缀(通常是"wp_")放入你的插件中。确认使用不同的$wpdb->前缀来代替。
  • 数据库阅读很简单但是写确很难,数据库是非常善于取数据给你,而且这些操作(通常是)如闪电般迅速。在数据库中做改动,却是一个复杂的多的过程,很难。所以试着最小化写入的数量。首先在你的代码中准备好一切,这样你只需要选择那些你需要的写操作。
  • 只选择你需要的。尽管数据库取数据非常快,你需要试着减少数据库的负载,通过只选择你需要的数据。如果你需要知道一个表格有多少行,不要SELECT * FROM,因为所有行中的所有数据都会被牵扯到,浪费内存。这样,如果你只需要插件中的post_id 和post_author,只要SELECT那些特定的区域,来减小数据库负载。记住: 大量的其他进程可能同时需要使用数据库。数据库和服务器每个都有大量的资源供这些进程使用。了解如何减小你的插件需要的资源会保证你的插件不会是被人说成滥用资源的哪种。


External Resources

外部资源