官术网_书友最值得收藏!

Actions versus Filters

This is another confusing area in the land of WordPress plugins. What exactly is the difference between an action and a filter? Well, even if you've read through the forums and official documentation, the answers there likely left you more confused, so let's get this clarified once and for all.

Actions and filters are simply two different types of events. Remember that WordPress refers to events as "hooks". The difference between them is predicated on how WordPress handles the hook in question. Some hooks are designated as action hooks, others as filter hooks. When you link one of your functions to a filter hook, your function must accept an input and return an output because it is intended to modify or "filter" output. When you link a function to an action hook, your function is not passed input parameters, and any value returned is simply ignored. It is all a matter of how WordPress handles a given hook. On his site, Adam Brown maintains lists of all available WordPress hooks, and you can verify whether a given hook is a filter or an action hook (http://adambrown.info/p/wp_hooks/).

The truth of the matter is that the architecture here is showing its age, and there are some caveats that can be confusing. Actions and filters are simply types of events, and the add_action() and add_filter() functions are actually one and the same—one function merely references the other. If you are curious, have a look for yourself inside the /wp-includes/plugin.php file. In other words, you can replace any instance of add_action() with add_filter() and vice versa, and it will have no effect on the functionality of your plugin. They both simply tie a WordPress event to a function you have defined. Even though the add_action() and add_filter() functions are fundamentally the same, we do not recommend that you swap them! There is a recommended usage here that should be followed for mnemonic purposes.

Just once, however, let's demonstrate that the add_action() and add_filter() functions are equivalent by modifying the "Hello Dolly" plugin once again. This will help us understand that both functions tie to an event, and the behavior of the event is determined by the event in question, not by the function used to reference it.

Exercise—actions and filters

Using your favorite text editor, let's modify the "Hello Dolly" plugin once more.

Try replacing both instances of add_action() with add_filter() and save the file. The following is what the important lines now look like:

add_filter('admin_footer', 'hello_dolly');
// ...
add_filter('admin_head', 'dolly_css');

Remember: We haven't changed anything else about this plugin, only these two lines.

Try refreshing the WordPress Dashboard—the plugin still functions in exactly the same way. The takeaways from this exercise should be that actions and filters are simply classifications of events, and the behavior of a particular event is inherent in the event itself, not in the function we use to reference it. In other words, admin_footer and admin_head are action-events, not filter-events, and they remain action-events no matter how we hook into them.

Return the functions to their original state once you're done:

add_action('admin_footer', 'hello_dolly');
// ...
add_action('admin_head', 'dolly_css');

Now that we've demonstrated that the event is the important thing here, not the function, let's try using a different event so we can see how it behaves differently.

Exercise—filters

Let's suppose we want to repurpose the "Hello Dolly" plugin so it prints random lyrics into posts on the frontend of our site instead of just inside the WordPress manager. We will call this new plugin "Hello Knock Off". The change in behavior will revolve around the event that we hook into. Instead of tying into the admin_footer event, we are going to hook into the the_content event. the_content is a filter event, so we have to use it slightly differently than we did the admin_footer action event. Comparing the "Hello Knock Off" plugin to the original "Hello Dolly" will be a simple example that demonstrates the differences between an action and a filter. Let's get started.

First, let's make a copy of the "Hello Dolly" plugin—just copy the hello.php file and name the copy knockoff.php. You should save it in the same directory: /wp-content/plugins. Be sure you deactivate the original "Hello Dolly" plugin to avoid confusion.

Next, modify the information header so we can spot this plugin inside the WordPress manager. The following is what our example looks like:

<?php
/*
Plugin Name: Hello Knock Off
Plugin URI: http://wordpress.org/#
Description: Our first filter event
Author: Some Puerto Rican Guy
Version: 0.1
Author URI: http://goo.gl/kMEc
*/

/*EOF*/

Activate the plugin from inside the WordPress manager—it should show up in the Plugin administration area under the name "Hello Knock Off". Before we change the functionality, verify that the copy of the plugin works just like the original. You should see the same random messages at the top of each page in your WordPress Dashboard just like you did with the original plugin.

Next, let's change the event that is referenced here. Instead of using the admin_footer hook, let's use the the_content hook. Change the following line:

add_action('admin_footer', 'hello_dolly');

So it reads:

add_filter('the_content', 'hello_dolly');

Even though we have demonstrated that both functions are effectively the same, do not confuse yourself or others by mixing these up! the_content is a filter event, so we should always reference it using the add_filter() function.

Save your work, then try visiting your home page. You'll notice that all of your posts have been replaced with random Hello Dolly lyrics, all simply because we are hooking the code into a different event.

Let's make some adjustments here so that instead of replacing the post content, we append the quote to it. That is what a filter normally does: it modifies some text, not replaces it entirely.

Edit the hello_dolly() function in your knockoff.php so that it accepts an input, and instead of echoing a string, it returns it:

function hello_dolly($input) {
   $chosen = hello_dolly_get_lyric();
   return $input . "<p id='dolly'>$chosen</p>";
}

The $input here represents the content for each post—it is passed into the filter function, acted on, and then returned. Do you see how we have appended the chosen lyric to the $input? The result is that now we are appending a random lyric to each blog post instead of overwriting it.

To reiterate what just happened, the bulk of changes were caused by simply changing the event that was referenced from admin_footer to the_content. We also had to change some of the syntax in the user-defined function to correctly use a filter event instead of an action event. This should help reinforce the fact that some events are filters, and some events are actions, and now you have seen the differences in syntax between these two types of events. A function called by an action event does not accept or return input, whereas a function called by a filter does.

You may have noticed that some parts of this knock-off plugin are not being used. So let's simplify our knock-off plugin by deleting the following two functions: dolly_css() and the function that hooks into it: add_action('admin_head', 'dolly_css');

Deleting those functions simply helps clean up superfluous code. The original "Hello Dolly" plugin required those extra functions in order to correctly style and position the output, but in our "Hello Knock Off" plugin, we don't need the extra styling because we are simply appending the quotes to post content.

Reading more

Hopefully these exercises have clarified how WordPress handles actions and hooks. It is worth your time and effort to skim through the online documentation that lists the most common actions and filters, just so you have some awareness of what actions and filters are available. WordPress has thousands of hooks, but there are still some key places that you cannot easily hook into. We recommend bookmarking the following two pages for reference:

http://codex.wordpress.org/Plugin_API/Action_Reference

http://codex.wordpress.org/Plugin_API/Filter_Reference

The hooks referenced on those pages are only a fraction of those available, but we recommend that you stick to the short list as much as possible. For a full list of all WordPress hooks, see:

http://adambrown.info/p/wp_hooks/

We have included a short list of actions and filters used in this book in Appendix B. You'll find that you can achieve a lot of what you need by using a small number of actions and filters.

主站蜘蛛池模板: 翁牛特旗| 定州市| 江油市| 湘西| 衡南县| 库尔勒市| 含山县| 巴楚县| 广宗县| 齐齐哈尔市| 抚顺县| 醴陵市| 陆良县| 娱乐| 兴城市| 广德县| 获嘉县| 绵竹市| 山阳县| 楚雄市| 陇南市| 四平市| 望江县| 盘锦市| 洞头县| 图们市| 辉南县| 南汇区| 成安县| 西乡县| 师宗县| 通许县| 长治县| 犍为县| 漳浦县| 津南区| 和龙市| 巴中市| 西青区| 姜堰市| 荣昌县|