Wordpress Plugin API overview

Source: Internet
Author: User
I. INTRODUCTION this article describes some APIs (programming language interfaces) provided for WordPress plug-in developers and how to call these interfaces. Before reading this article, please refer to the development of a plug-in to learn more about the plug-in overview and details. The text focuses on the & ldquo; execution hooks & rdquo; class interfaces, which are also called & ldquo; filter & rdquo; (Filters) I. INTRODUCTION

This article describes some APIs (programming language interfaces) provided for WordPress plug-in developers and how to call these interfaces.

Before reading this article, please refer to the development of a plug-in to learn more about the plug-in overview and details. The text focuses on the interfaces of the "execute hook" class. these interfaces are also called "Filters" and "Actions ), wordPress uses this interface to mount the plug-in to the system. Of course, you can also call this type of interface in the topic file. for details, refer to: topic function file.

Note:? This article applies? WordPress 1.2? Or later. For versions earlier than 1.2, only the source code of WordPress can be modified to expand the system.

 

II. execution hooks, actions, and filters

WordPress has a mechanism called "execute check", which allows the plug-in to "mount" some features into WordPress. That is to say, when the system runs to a certain stage, it calls some functions in the plug-in. There are two types of execution hooks:

  1. Action: An Action is a hook that is executed when WordPress runs to a certain stage or when an event occurs. Any plug-in can use the action interface to instruct the system to execute the specified PHP function when encountering these links or events.
  2. Filter: a Filter is a hook used by WordPress to modify the data to be saved or sent out. Any plug-in can use the filter interface to indicate that when the system encounters certain links or events, it will execute the specified PHP function to modify specific data.

Sometimes actions or filters can achieve the same effect. For example, if you want to modify the content of an article, can you mount the plug-in to the action?Publish_post? , Modify the content of the article before saving it to the database. Can I also mount the plug-in to a filter?The_content? , Modify the content of the article before it is sent to the browser.

To query all the standard actions and plug-ins in WordPress, see :? Adam Brown's WordPress execution hooks the database.

 

III. Function Reference
Filter functions
  • Has_filter
  • Add_filter
  • Apply_filters
  • Current_filter
  • Merge_filters
  • Remove_filter
  • Remove_all_filters
Action functions
  • Has_action
  • Add_action
  • Do_action
  • Do_action_ref_array
  • Did_action
  • Remove_action
  • Remove_all_actions
Activate and shield functions
  • Register_activation_hook
  • Register_deactivation_hook
IV. action

Actions)? It is triggered by some events in WordPress, such as posting an article, changing a topic, or accessing a management interface in the background. these are examples of events. The plug-in can specify some PHP functions to respond to the actions triggered by these events. For example:

  • Modify database data
  • Send email
  • Modify the content to be displayed

Follow these steps:

  1. Define the PHP function to be executed when an event occurs in the plug-in code.
  2. UseAdd_action ()? Register this function to the action execution check.
  3. Place the plug-in source code in the place specified by WordPress and enable it.

 

Define action response functions

To execute actions in the plug-in, you must first putWp-content/plugins. For example, in the following example, the function is to notify friends by email when a new article is published.

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;}

In most actions, a parameter is passed to the function that responds to it (based on the actual situation, it may be the article ID or the comment ID ). Some actions will pass multiple actions. for details, see the document and the WordPress source code. Of course, in addition to the passed parameters, the response function can also call WordPress global variables and functions, or call plug-in custom variables and functions.

If the plug-in contains commands that directly output results (such as print or echo), the output content will appear in the corresponding place of the page based on the execution time of the action.

Note:: When defining a function in a plug-in, it may have the same name as other plug-ins or functions in WordPress. Therefore, before naming a function, see: avoid name conflicts.

 

Mount to WordPress

After defining the action response function, you need to mount (or register) the function to WordPress. Is it called in the plug-in?Add_action ()? Function:

Add_action ('Action name', 'response function name', [priority], [number of parameters]);

Parameter description:

Action name?
The action name provided by WordPress, used to identify the action in which the response function is executed
Response Function name?
When action? Hook_name? The name of the response function to be executed when it occurs. Can it be a PHP Standard function, a WordPress function, or a custom function in the plug-in, such as in the above example? 'Email _ DS'
Priority?
This is an optional parameter. the default value is 10. Since multiple functions can be registered to the same action, this parameter is used to specify the priority of the function execution registered to this action. The smaller the number, the higher the priority, the earlier the execution, and vice versa. If several functions are registered to the same action with the same priority, the execution order is determined by the order in which they are registered.
Number of parameters?
This is an optional parameter. check that the value is 1. Some actions may pass multiple parameters to the response function. Therefore, you must specify the number of parameters that the response function can accept. This parameter is added in version 1.5.1.

If we come back to discuss the previous example, we can mount the function to the system as follows:

add_action ( 'publish_post', 'email_friends' );

You can also delete an action after the action is attached.

 

Install and enable

After installing the file and activating the plug-in, you can use the action hook. Your PHP functions and?Add_action? The call must be stored in the same PHP file, and the PHP file must be installed (saved)Wp-content/pluginsDirectory. Once the installation is successful, you will need to open the WordPress administrator page and activate your plug-in. For more information, see manage Plugins.

 

Category hooks currently provided

See? Plugin API/Action Reference? To find the list of currently provided WordPress category hooks and links to the category hooks of WordPress in the past.

 

5. filter

FilterIs a type of function. during the process of WordPress's data transmission and processing, run at a specific point before performing certain actions on the data (for example, writing data to a database or passing it to a browser page ). The filter is in the middle of the database and the browser (when WordPress is generating a page), and is in the middle of the browser and the database (when WordPress adds a new article comment to the database ); most of the input and output in WordPress are filtered by at least one filter. WordPress performs some filtering by default, and your plug-in can add its own filter.
The basic steps for adding your own filter to WordPress are as follows (more details are described below ):

  1. Create a PHP function to filter data.
  2. Access the filter through hooks in WordPress and referenceAdd_filter
  3. Put your PHP function into a plug-in file and activate it.

 

Create filter functions

A filter function plays a role when the input data is not adjusted and returns the adjusted data (or in some cases, a null value indicates that the data should be deleted or ignored ). If the data is not processed by your filter, the initial data must be returned, so that subsequent plug-ins can continue to correct its value when necessary.
Therefore, the first step to create a filter in your plug-in is to create a PHP function to execute the filter and store it in your plug-in file (your plug-in file must be placed inWp-content/pluginsDirectory ). For example, if you need to confirm that your article or comment does not contain foul words, you can define a global variable that contains a list of disabled words and then create the following PHP function:

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

Note:: Always pay attention to whether the function name you think of may be used in other plug-ins or WordPress core functions. See Plugin Development Suggestions for more information.

 

Hook your filter

After your function definition is complete, the next step is to hook in or register it in WordPress. To achieve this, you can reference the global execution space of your plug-in.Add_filter:

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

Where:

Hook_name?
The filter hook provided by WordPress defines when your filter will be executed.
Your_filter?
The name of the function you want to use to perform the filtering function. This can be a standard PHP function, a standard WordPress core function, or a function you have defined in a plug-in file.
Priority?
Optional. integer parameter, used to determine the order of the functions associated with a specific filter during execution (10 by default ). Functions with the same priority are added to the filter in the order they are executed.
Accepted_args?
(Optional) integer parameter, which defines how many parameters your function can accept (default value: 1 ). It has some value, because some hooks will pass more than one parameter to your function.

In the example above, we wocould put the following in the main executing section of the plugin file, to tell WordPress to filter comments for profanity, we should put the following code into the main execution segment of the plug-in file to tell WordPress to filter out swearing comments:

add_filter('comment_text','filter_profanity');

You can also useRemove_filter ()The function removes the filter from the filter hook. See Removing Actions and Filters.

 

Install and activate

To make your hook take effect, the last step you need to do is to install and activate the plug-in. The PHP functions you wrote andAdd_filterIt must be in a php file and must be installed inWp-content/pluginsDirectory. After the installation is complete, you need to access the WordPress background and then activate your plug-in. For more information, see manage Plugins.

 

Hooks currently provided for filters

See? Plugin API/Filter Reference? Find the hooks currently provided for the WordPress filter and links to the WordPress hooks of previous versions.

 

Example

As described by Ozh in the wp-hackers email list, is this plug-in used to modify (or overwrite) the default?bloginfo()? Function. This requires modifying the behavior of a core function.

add_filter('bloginfo', 'mybloginfo', 1, 2);add_filter('bloginfo_url', 'mybloginfo', 1, 2);function mybloginfo($result='', $show='') {        switch ($show) {        case 'wpurl':                $result = SITE_URL;                break;        case 'template_directory':                $result = TEMPL_DIR;                break;        default:         }        return $result;}

 

6. remove hooks and filters

In some cases, you will find that you need to disable your plug-in or other plug-ins to create an action or filter for WordPress. You can referenceRemove_filter ('filter _ hook ', 'filter _ function ')OrRemove_action ('Action _ hook ', 'Action _ function ').

For example,Remove_action ('Publish _ post', 'generic _ ping ');It will prevent your blog from sending pings values at any time when your new blog posts.

Note: if a hook is registered with a function that exceeds the default value of 10, you must also useRemove_action ()Specify priority. Also note that you should not remove anything unless you know what it is and why it is done-check WordPress or other plug-in code to confirm.

 

7. system functions you can rewrite

In addition to the hooks (actions and filters) described above, there is another plug-in method to handle WordPress behavior, that is, rewrite the WordPress function. In fact, a small part of the functions are WordPress ready for redefinition. These functions are loaded only when all plug-ins are loaded and they are not redefined. Viewwp-settings.phpLearn more.

These functions are defined inwp-includes/pluggable.php. Here is a table of version 2.7.1. a few of these documents can be found in Function Reference.

  • Set_current_user
  • Wp_set_current_user
  • Wp_get_current_user
  • Get_currentuserinfo
  • Get_userdata
  • Update_user_cache
  • Get_userdatabylogin
  • Get_user_by_email
  • Wp_mail
  • Wp_authenticate
  • Wp_logout
  • Wp_validate_auth_cookie
  • Wp_generate_auth_cookie
  • Wp_parse_auth_cookie
  • Wp_set_auth_cookie
  • Wp_clear_auth_cookie
  • Is_user_logged_in
  • Auth_redirect
  • Check_admin_referer
  • Check_ajax_referer
  • Wp_redirect
  • Wp_sanitize_redirect
  • Wp_safe_redirect
  • Wp_policy_postauthor
  • Wp_policy_moderator
  • Wp_password_change_notification
  • Wp_new_user_notification
  • Wp_nonce_tick
  • Wp_verify_nonce
  • Wp_create_nonce
  • Wp_salt
  • Wp_hash
  • Wp_hash_password
  • Wp_check_password
  • Wp_generate_password
  • Wp_rand
  • Wp_set_password
  • Get_avatar
  • Wp_setcookie
  • Wp_clearcookie
  • Wp_get_cookie_login
  • Wp_login
  • Wp_text_diff

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.