FANDOM


插件接口(API)

介绍编辑

这篇文章主要是为 WordPress 的插件开发者们介绍可用的钩子API(应用程序接口). 这些内容适用于 WordPress 的 1.2 或更高版本. 在1.2版本之前,修改被称做"hacks", 那时我们得自己去修改WordPress的源代码, 可想而知,那是件非常郁闷的事情.(这句可能翻译的不好,留下原文)(modifications were called "hacks" and involved editing the source code of WordPress itself.)

wp-plugins.org是 Wordpress 官方的开发和发布插件的网站, 它包含了版本控制和bug跟踪工具.wp-plugins.org是一个非常优秀的网站,我们向所有的 WordPress 插件开发者推荐.

Hello Dolly 是 WordPress 的第一个插件. 阅读它的源码能够帮助你理解插件的工作方式,并且能够指导你构建属于自己的插件. 这里还有一篇介绍性的文章(PartI) (Part II) 也许会对你有所帮助. 如果你需要一些关于数据库表的简单说明,你可以访问 数据库说明 页面.

友情提示: 编写插写 是插件开发者必读的一篇文章. 这篇文章清楚的描述了插件开发的总体情况, 并且表述了如何 添加管理员菜单 , 如何 添加选项, 还有 插件指南 等信息, 除此之外,在这篇文章里,你还能找到许多有用的小技巧.

钩子,行为及过滤器 编辑

WordPress 提供钩子的形式允许你将你的插件"钩入"(hook into)系统. WordPress 包含两种类型的钩子:

  1. 行为钩子:行为是一些能够由 WordPress 核心事件触发的函数(有点像 .Net 中的委托).行为钩子能够让你添加或移除由WordPress行为触发执行的函数.这些钩子能够使插件在它们指定的行为被触发执行.
  2. 过滤器钩子:过滤器是修改WordPress存储在你数据库中的内容的函数.过滤器钩子允许你为WordPress的不同类型的内容(通常为文本)添加或者移除过滤器.这些钩子能够使你能够非常容易的修改内容或者文本.

站在编码人员的角度来看,行为和过滤器是非常相近的. 比如add_action 函数和add_filter 函数几乎没有什么差别.但是在实践中,它们的使用却不尽相同.

在有个时候,你也可以用行为或者过滤器达到同样的目的.比如说,为publish_post 添加一个行为,或者为the_content添加一个过滤器都可以访问文章内容. 这两个选择的根本在于你只想改变内容一次,还是想每次都提交内容的时候都对内容进行访问和更改.

行为 编辑

行为 是由 WordPress 指定的事件触发的, 比如发布文章, 修改皮肤, 显示管理面板页面. 行为对于用来响应博客的更改是非常有用的,但它们也有以下两个基本的用途:

  1. 在指定的行为被触发时以修改数据库数据或者发送 Email的方式做出响应.
  2. 在Blog或者WordPress的管理界面的指定位置显示内容.

增加行为 编辑

要使用行为插件钩子, 首先得为你的插件创建一个php函数:

function email_friends($post_ID)  {
   $friends = 'bob@example.org,susie@example.org';
   mail($friends,"sally's blog updated",'I just put something on my blog:
   http://blog.example.com');
   return $post_ID;
}

你的函数应该能够接收一个的参数,通常这个参数为文章ID或者回复ID,但是如果它并不在下面的列表中存在,你需要在 WordPress source code 页面中搜索并确认一下--搜索文本"do_action"并且检查它的其它参数.

友情提示: 其它的插件可能会使用和你新建的插件一样的名称.你可以查找避免函数命名冲突 获得更多的信息.

行为能够操作 WordPress 的全局变量,如表格变量$wpdb.

在你完成你的功能以后,在全局执行的地方使用add_action() 方法将其注册到 WordPress. 如:

add_action ( 'hook_name', 'your_function_name', [priority], [accepted_args] );

其中:

  1. hook_name 是 WordPress 提供的一个行为钩子.某些钩子会传递一个参数,你可以在'your_function_name' 函数中接收这个参数.
  2. your_function_name 是你希望能在hook_name. 的事件被触发后调用的函数.它可以是一个php自带的函数,一个WordPress提供的核心函数,或者是一个在你插件文件中自定义的函数.
  3. priority 是一个整型的可选参数.它用来指定绑定同一行为的函数的执行顺序.如果你没有传入这个参数,你的函数的优先级将被设置为默认的10. 一个拥有优先级1 的函数将会比拥有优先级 2, 的函数先被调用执行,所以,数字越小,其优先级将越高.同一优先级的函数将被按函数的注册顺序执行.
  4. accepted_args 是一个可选的整型参数,它定义你的函数能接收多少个参数.因为有些钩子能向的函数传递多余一个的参数.accepted_args的默认值为1.这个参数是在1.5.1版中新增的.

例如:

add_action('publish_post', 'email_friends');
function email_friends($post_ID)  {
 ...
}

同样的,你也可以从行为钩子中Removing Actions and Filters|移除]] 行为.你可以左边的链接中获得详细信息.

wp-content/plugins 文件夹中新建一个文件,然后将你的代码保存到那个文件中.

访问 管理插件 了解如何激活插件.

当前提供的行为钩子 编辑

NOTE: the following list is not a comprehensive listing of hooks. See Skippy's list for a more comprehensive, if less descriptive, listing of actions and filters. Also, for a current list, with documentation, visit WordPress Hooks, a work in progress directory of all of WordPress’ hooks.

See Angsuman's list for a comprehensive listing of WordPress action hooks with documentation and source code location information. It contains all documented and undocumented action hooks in WordPress 2.0.

admin_footer 
No parameter. Executes at the end of the admin panel inside the body tag. Useful for insertion of additional content.
admin_head 
No parameter. Executes in the <head> section of the admin panel. Useful for insertion of additional content.
admin_menu 
No parameter. Executes after the basic admin panel menu structure is in place. Useful for adding additional menus to the admin panel.
comment_closed 
Receives the comment's post ID as a parameter. Executes when attempting to display the comment form for a post that has closed comments.
comment_form 
Receives the comment's post ID as a parameter. Template tag. Executes after displaying the comment form for a post that allows comments.
comment_id_not_found 
Receives the comment's post ID as a parameter. Executes when attempting to display the comment form for a post that does not exist.
comment_post 
Receives the comment ID as a parameter. Executes when a comment is added through wp-comments.php.
delete_comment 
Receives the comment ID as a parameter. Executes when a comment is deleted.
delete_post 
Receives the post ID as a parameter. Executes whenever a post is deleted.
edit_comment 
Receives the comment ID as a parameter. Executes whenever a comment is edited.
edit_form_advanced 
No parameter. Executes during the display of the admin panel's advanced editing page, just before the <div> is closed that contains the post content textarea. Useful for inserting additional input fields into the advanced editing form.
edit_page_form 
No parameter. Executes inside the <form> tag on the page editing form. Useful for inserting additional input fields in the page editing form.
edit_post 
Receives the post ID as a parameter. Executes every time a post is edited.
generate_rewrite_rules 
No parameter. Executes whenever the rewrite rules are recomputed. To modify the computed rules, use the filter rewrite_rules_array instead.
init 
Executes after WordPress has finished loading but before any headers are sent. Useful for intercepting $_GET or $_POST triggers.
pingback_post 
Receives the comment ID as a parameter. Executes when a comment is added via XMLRPC.
private_to_published 
Receives the post ID as a parameter. Executes when a post is moved from private to published status.
publish_phone 
Receives the post ID as a parameter. Executes when a post is added via wp-mail.php.
publish_post 
Receives the post ID as a parameter. Executes when a post is saved and its status is set to "publish", regardless of its prior setting. NOTE: to add a hook to this action in 1.2, be sure to specify a priority between 0 and 9. The generic_ping hook is buggy and prevents any lesser priority hooks from working.
save_post 
Receives the post ID as a parameter. Executes when a post is saved to the database.
shutdown 
No parameter. Executes when the page output is complete.
simple_edit_form 
No parameter. Executes during the display of the admin panel's simple editing page, just before the <div> is closed that contains the post content textarea. Useful for inserting additional input fields into the simple editing form.
switch_theme 
Receives the name of the current theme as a parameter. Executes when the blog theme is changed.
template_redirect 
No parameter. Executes before the determination of the template file to be used to display the requested page. Useful for providing additional templates based on request criteria. Example (pedagogical, not useful): Redirect all requests to the all.php template file in the current themes' directory.
function all_on_one () {
	include(TEMPLATEPATH . '/all.php');
	exit;
}

add_action('template_redirect', 'all_on_one');
trackback_post 
Receives the comment ID as a parameter. Executes when a comment is added via trackback.php.
wp_footer 
No parameter. Template tag. Executes at the end of the <body> tag. Useful for insertion of additional content.
wp_head 
No parameter. Executes in the <head> section. Useful for insertion of additional content.
wp_meta 
No parameter. Executes in the <li>Meta</li> section of the included Theme's sidebar.php's. Useful for insertion of additional content.
wp_set_comment_status 
Receives the comment ID as a parameter. Executes when the comment status changes.

过滤器 编辑

Filters

Filters are functions through which data flows or is changed. They're good for making on-the-fly changes to data (like adding acronyms to certain words).

Your function must return the modified value. If the value is not modified, then the original value that is passed must be returned so that subsequent plugins can continue to modify the value if necessary. If you do not return a value, the value will be empty when returned to the next plugin, which might break other plugins!

In 1.2 generic_ping (hooked to publish_post) does not do this and as a result any lesser priority hooks to publish_post do not work.

使用过滤器 编辑

Filters are sitting between the database and the browser. Everything that flows from the database to the browser has to pass through a filter. By adding a filter you can change what the user sees without changing the content of your database. On the other hand, other filters can preprocess the inputs before their storage in your database.

Create a php function that processes text, like so:

function filter_profanity($content) {
   global $profanities;
   foreach($profanities as $profanity) {
       $content=str_ireplace($profanity,'{censored}',$content);
   }
   return $content;
}

(you don't actually have to write your own functions--any standard php function that processes text can be used (strtoupper, for example).

NOTE: If you do write a new function (and chances are you will at some point), keep in mind that another plugin may already be using the name of your new function as the name of one of its own. See Avoiding Function Name Collisions for more information.

Outside of your function (in the general execution space) add your new filter to a filter hook:

add_filter('hook_name', 'your_filter', [priority], [accepted_args]);

where,

  1. hook_name is a Filter Hook provided by WordPress
  2. your_filter is the name of the function that you want to use on the content specified by filter_hook. This can be a standard PHP function, a function present in the WordPress core, or a function defined by you in the plugin file.
  3. priority is an optional integer argument that can be used to specify the order in which filters for a particular filter hook are applied. If you do not specify this argument, your filter will be given the default priority 10. A filter with a priority of 1 is applied before a filter of priority 2, so the smaller the integer, the higher the priority. Filters with the same priority are applied in the order in which they were added to the filter hook.
  4. accepted_args is an optional integer argument defining how many arguments your function can accept. Some hooks can pass more than one argument to your function. The default is 1. This parameter is new in release 1.5.1.


The above example might be added like so:

add_filter('comment_text','filter_profanity');

You can remove filters from filter hooks using the WordPress function remove_filter(). See Removing Actions and Filters.

当前提供的过滤器钩子 编辑

See Angsuman's list for a comprehensive listing of WordPress filters with documentation and source code location information. It contains all documented and undocumented filters in WordPress 2.x.


Notice that most of these are Template Tags.

author_email  
TBD
bloginfo  
TBD
category_description  
applied to the "description" field of comments.
comment_author  
TBD
comment_edit_pre  
applied to comment content prior to display in editing screen
comment_email  
TBD
comment_excerpt  
TBD
comment_save_pre  
applied to comment content when re-saving comment from admin pages
comments_number  
TBD
comment_text  
passed the comment text, as a string. The following (silly) plugin snippet would make all the comments display in boldface, but would not alter the comment text as stored in the database.
function bold_comment($comment = '') {
     return "<strong>$comment</strong>";
}

add_filter('comment_text', 'bold_comment');
comment_url  
passed the commenter's URL, if supplied. The following sample plugin will prepend all URLs with the Google redirector, without modifying the URL as stored in the database:
function google_redirect($url = '') {
     if ('' != $url) {
          return "http://www.google.com/url?sa=D&amp;q=$url";
     }
}
add_filter('comment_url', 'google_redirect');
content_edit_pre  
TBD
content_save_pre  
applied to post content when saving post from admin pages or XML-RPC
default_content  
Allows a plugin to modify the default value for the content of a new post.
default_excerpt  
Allows a plugin to modify the default value for the excerpt of a new post.
default_title  
Allows a plugin to modify the default value for the title of a new post.
excerpt_edit_pre  
TBD
excerpt_save_pre  
TBD
format_to_edit  
Allows a plugin to modify the data stored for a post before it is displayed for editing in the post editor.
format_to_post  
TBD - Uncalled in current source.
get_comment_author_url  
use this instead of the comment_url filter
get_comment_author_link  
returns the HTML for comment author's link with comment author's name
link_rating  
Allows a plugin to modify the stored value of a link rating before it is used.
list_cats  
called at two different times:
  1. once for each entry in the category list when wp_list_cats() or list_cats() is referenced in a theme. First parameter is the category name. The second optional parameter (for 1.5.1) is the category object.
  2. at the end of the category list. First parameter is the entire text of the list. No second parameter is passed.

If the second parameter is desired, be sure to provide a default value. Example that prints the category ID after the name and "end of list" at the bottom:

function foo_bar($content, $category = null) {
	if ($category == null) {
		return $content . '<li>(end of list)</li>';
	}
	else {
		return $content . " (ID={$category->cat_ID})";
	}
}

add_filter('list_cats', 'foo_bar', 10, 2);
loginout  
Allows a plugin to modify the tag and text produced that link to the WordPress login page.
mod_rewrite_rules  
passed the block of rules as a string. The rules are formatted as they will/should be written out to your .htaccess file.
page_link  
Allows a plugin to modify auto-generated (i.e. via template tag) links to static pages.
phone_content  
Allows a plugin to modify the content gathered from a post-by-email post before it is saved.
posts_where  
Allows a filter to change the WHERE clause of the query that returns the post array.
posts_where_paged  
Allows a filter to change the WHERE clause of the query that returns the post array, executes after the default paging WHERE clause is generated.
posts_join  
Allows a plugin to modify the JOIN clauses of the query that returns the post array. This is typically used to add a table to the JOIN, in combination with the posts_where trigger.
posts_join_paged 
Allows a plugin to modify the JOIN clauses of the query that returns the post array, executes after the default paging JOIN clauses are generated.
post_link 
Allows a plugin to modify auto-generated (i.e. via template tag) links to posts.
posts_orderby 
Allows a plugin to modify the ORDER BY clause of the query that returns the post array.
preprocess_comment  
preprocessing a comment, called with the comment passed as an array. Should return a array. The indices of the array are comment, comment_post_ID, user_ID, user_ip, user_domain, user_agent, author, email, url, approved.
pre_comment_approved  
Before a comment is stored in the database, this filter provides access to the current approval setting of that comment. Global variables can be used to access the comment data itself.
pre_commment_author_name  
preprocessing a new comment's author name prior to saving it in the database, called with the author name passed as a string. Should return a string.
pre_comment_author_email  
preprocessing a new comment's author email prior to saving it in the database, called with the author email passed as a string. Should return a string.
pre_comment_author_url  
preprocessing a new comment's comment author URL prior to saving it in the database, called with the author URL passed as a string. Should return a string.
pre_comment_content  
preprocessing a new comment's content prior to saving it in the database, called with the comment content passed as a string. Should return a string.
pre_comment_user_agent  
TBD
pre_comment_user_domain  
TBD
pre_comment_user_ip  
TBD
query_string  
TBD
register  
Allows a plugin to modify the tag and text produced that link to the WordPress registration page.
rewrite_rules  
deprecated in 1.5, see mod_rewrite_rules.
rewrite_rules_array  
TBD
sanitize_title  
TBD
single_post_title  
TBD
stylesheet  
TBD
template  
TBD
the_category  
TBD
the_category_rss  
TBD
the_content  
applied to post content prior to rendering. Passed the content as a string. The following plugin snippet would replace all instances of the word foo with bar, without modifying the contents of the post as stored in the database:
function foo_bar ($content = '') {
     return preg_replace("/foo/", "bar", $content);
}

add_filter('the_content', 'foo_bar');
the_date  
TBD
the_excerpt  
TBD
the_excerpt_rss  
TBD
the_posts  
TBD
the_time  
TBD
the_title  
TBD
the_title_rss  
TBD
the_weekday  
TBD
the_weekday_date  
TBD
title_edit_pre  
TBD
xmlrpc_methods  
Applied to list of methods passed to the constructor for the XML-RPC server. This means you can add/remove/override the standard method list.

Rich Editor Filters 编辑

These filters modify the configuration of the rich editor.

mce_browsers
The browsers supported by the rich editor. Input and output is an array of strings, which defaults to array('msie', 'gecko', 'opera').
mce_theme 
The visual and functional theme of the rich editor. Filters using this hook should replace, not append the data they receive, which defaults to 'advanced'.
mce_plugins 
The plugins loaded by the rich editor. Filters using this hook should append the array they receive. The input and output is an array of strings. The data defaults to:
     array('wordpress', 'autosave', 'wphelp')
An example function to add your own plugin:
     add_filter('mce_plugins', 'extended_editor_mce_plugins', 0);
     function extended_editor_mce_plugins($plugins) {
         array_push($plugins, 'plugin_name');
         return $plugins;
     }
mce_valid_elements 
The valid html elements for the rich editor. Any elements not in this list will automatically be removed by the rich editor BEFORE the post is submitted to WordPress. The input and output is a single comma-delimited string of elements. See http://tinymce.moxiecode.com/tinymce/docs/option_valid_elements.html for more detailed information.
An example function to add your own valid elements (without overriding the defaults):
     add_filter('mce_valid_elements', 'extended_editor_mce_valid_elements', 0);
     function extended_editor_mce_valid_elements($valid_elements) {
         $valid_elements .= 'element1,element2';
         return $valid_elements;
     }
mce_buttons, mce_buttons_2, mce_buttons_3 
The rows of buttons in the toolbar displayed by the rich editor. Filters using these hooks should append to the mce_buttons_2 or mce_buttons_3. The input and output is an array of strings.
mce_buttons defaults to array('bold', 'italic', 'strikethrough', 'separator', 'bullist', 'numlist', 'outdent', 'indent', 'separator', 'justifyleft', 'justifycenter', 'justifyright' ,'separator', 'link', 'unlink', 'image', 'wordpress', 'separator', 'undo', 'redo', 'code', 'wphelp')
mce_buttons_2 and mce_buttons_3 default to empty arrays (array()).
An example function to add your own button after a separator on the right of the first row:
     add_filter('mce_buttons', 'extended_editor_mce_buttons', 0);
     function extended_editor_mce_buttons($buttons) {
         array_push($buttons, 'plugin_name');
         return $buttons;
     }

模版过滤 编辑

You can apply filters to Templates with the following filter hooks. See also the template_redirect action hook above.

404_template 
archive_template 
author_template 
category_template 
date_template 
home_template 
page_template 
paged_template  
(may be eliminated see notes on bug 825)
search_template 
single_template 
comments_popup_template 

移除行为和过滤器 编辑

You're not the only one using the API--this is the same technique that the developers use to achieve all sorts of effects. You might need to remove some of these for your plugin to work. You can do that by calling remove_filter('hook','filter') or remove_action('hook','action').

For example: remove_action('publish_post','generic_ping'); would prevent your weblog from sending pings whenever a new post is created.

If a hook was registered using a priority other than the default of 10, then you must also specify the priority in the call to remove_action().

In general, you shouldn't remove anything unless you know what it does and why it does it. The filename in which the hook is added is provided to make it easy for you to check out.

Filters and Actions Applied By Default 编辑

WordPress 1.5 编辑

Default filters and actions are defined in wp-includes/default-filters.php. Please see that file in WordPress' most recent release.

WordPress 1.2 编辑

post related

wp-rdf.php:add_filter('the_content', 'trim');
template-functions-post.php:add_filter('the_content', 'convert_smilies');
template-functions-post.php:add_filter('the_content', 'convert_chars');
template-functions-post.php:add_filter('the_content', 'wpautop');
vars.php:add_filter('the_content', 'wptexturize');
functions.php:add_action('publish_post', 'generic_ping');
template-functions-post.php:add_filter('the_excerpt', 'convert_smilies');
template-functions-post.php:add_filter('the_excerpt', 'convert_chars');
template-functions-post.php:add_filter('the_excerpt', 'wpautop');
vars.php:add_filter('the_excerpt', 'wptexturize');

title-related

template-functions-post.php:add_filter('the_title', 'convert_chars');
template-functions-post.php:add_filter('the_title', 'trim');
vars.php:add_filter('the_title', 'wptexturize');
vars.php:add_filter('single_post_title', 'wptexturize');
template-functions-post.php:add_filter('the_title_rss', 'strip_tags');
functions-formatting.php:add_action('sanitize_title', 'sanitize_title_with_dashes');

comment-related

template-functions-comment.php:add_filter('comment_excerpt', 'convert_chars');
kses.php:add_filter('comment_author', 'wp_filter_kses');
template-functions-comment.php:add_filter('comment_author', 'wptexturize');
template-functions-comment.php:add_filter('comment_author', 'convert_chars');
vars.php:add_filter('comment_author', 'wptexturize');
template-functions-comment.php:add_filter('comment_email', 'antispambot');
template-functions-comment.php:add_filter('comment_url', 'clean_url');
wp-comments-popup.php:add_filter('comment_text', 'popuplinks');
template-functions-comment.php:add_filter('comment_text', 'convert_chars');
kses.php:add_filter('comment_text', 'wp_filter_kses');
template-functions-comment.php:add_filter('comment_text', 'make_clickable');
template-functions-comment.php:add_filter('comment_text', 'wpautop', 30);
template-functions-comment.php:add_filter('comment_text', 'balanceTags');
template-functions-comment.php:add_filter('comment_text', 'convert_smilies', 20)
;
vars.php:add_filter('comment_text', 'wptexturize');

category-related

vars.php:add_filter('category_description', 'wptexturize');
vars.php:add_filter('list_cats', 'wptexturize');

miscellaneous

vars.php:add_action('wp_head', 'doGeoUrlHeader');