WordPress Plugin Development

WordPress plugin hooks

Our plugin now works fine, but there is a problem. In order to use it, we also have to edit the
theme. This can be a real pain for all sorts of reasons:

  • If you want to change to a diff erent theme, the plugin will stop working until you
    edit the new theme.
  • If you want to distribute your plugin to other people, they can’t just install it and
    activate it; they have to change their theme files too.
  • If you change the function name, you need to alter the theme files again

We need some way to make the plugin work on its own, without the users having to change
their themes or anything else.

Hooks come to the rescue, making it possible to display our Digg This butt on in our
posts—without ever modifying our theme.

Time for Action – Use a filter hook

We will use the the_content filter hook to automatically add our Digg This link to the end
of the post content. This will avoid the need for the users to edit their theme files if they
want to use our plugin.

  1. Create a function that we will use to hook to the content filter:

    
    	// create a Digg link and return it
    	return '<a href="http://digg.com/submit?url='.$link.'&
    		title='.$title.'&bodytext='.$text.'">Digg This</a>';
    	}
    	/* Add Digg link to the end of the post */
    	function WPDiggThis_ContentFilter($content)
    	{
    		return $content.WPDiggThis_Link();
    	}
    

  2. Use the post content hook to automatically call our new function:
  3. 
    	add_filter('the_content', 'WPDiggThis_ContentFilter');
    

  4. Remove the references to our function from the theme template as we no longer
    need them. Leaving them would have the eff ect of showing the link twice.

The end result is now the same, but we now control the appearance of the link directly
from our plugin.

What just happened?

When we activate our plugin now, WordPress comes across and runs this line:


	add_filter('the_content', 'WPDiggThis_ContentFilter');

This tells WordPress that every time it’s going to display the content of a post or page, it
should run it through our WPDiggThis_ContentFilter() function. We don’t need to
modify the theme file anymore – WordPress will make sure that the function runs at the
required time.

When we load a post now, WordPress will automatically call our function:


	/* Add Digg link to the end of the post */
	function WPDiggThis_ContentFilter($content)
	{
		return $content.WPDiggThis_Link();
	}

This function receives the post’s content as a parameter, and returns the filtered content. In
this case, our Digg link gets automatically appended to the end of the content.

WordPress hooks

WordPress provides a powerful mechanism for plugin functions to be called at the exact time
when we need them. This functionality is accomplished by using the so called hooks.

Every time you call a page from your browser, the WordPress engine goes through every
possible function it needs to render the requested page. Somewhere along the way, you can
“hook” up your function and use it to aff ect the end result.

You do this by simply registering your function with a specified hook, allowing it to be called
by WordPress at the right moment.

There are two types of WordPress hooks:

  • Action hooks: These are triggered by WordPress events, for example, when
    someone creates a post or writes a comment.
  • Filter hooks: These are used to modify WordPress content on the fl y, like title or
    content of the post as it is being served to the user.

Filter hooks

We learned that filter hooks (also referred to as simply ‘filters’) are functions that process
WordPress content, whether it is about to be saved in the database or displayed in the user’s
browser. WordPress expects these functions to modify the content they get and return it.

In our case, we used the_content filter hook to modify the post content by appending a
Digg link to it. We could also have placed the Digg link at the beginning of the post, or broken
up the post and put it in the middle.

To set up a filter, we need to use the add_filter function:


add_filter ( 'filter_hook', 'filter_function_name' , [priority],
[accepted_args] );

  • filter_hook: One of the filter hooks provided by WordPress.
  • filter_function_name : A function used to process the content provided by the
    filter_hook.
  • priority : An optional parameter, which specifies the execution order of functions.
    The default value is 10 if several functions apply to the same filter hook, functions
    with a lower priority number execute first, while the functions with the same
    priority will execute in the order in which they were added to the filter.
  • accepted_args: An optional parameter, which specifies how many arguments
    your function can accept. The default value is 1. The accepted_args parameter is
    used for hooks that pass more than one argument.

Here is an example list of filter hooks, which will help you to get a bett er understanding of
what you can achieve using them.

Filter hooks can be removed using the remove_filter() function. It accepts the same
arguments as add_filter(), and is useful if you want to replace some of the existing
WordPress filters with your functions.

If you want to take a closer look at the default WordPress filters, you can find them in the
wp-includes\default-filters.php file of your WordPress installation.


	It is important to remember that the filter function always receives some data and
	is responsible for returning the data, whether it modifies the data or not. Only if
	you want to disregard this data completely, can you return an empty value.

Action hooks

We use action hooks when we need to include specific functionalities every time a
WordPress event triggers, for example when the user publishes a post or changes the theme.

WordPress does not ask for any information back from the action function, it simply
notifies it that a certain event has happened, and that a function should respond to it
in a desired way.

Action hooks are used in a way similar to the filter hooks. The syntax for setting up an action
hooks is:


	add_action ( 'action_hook', 'action_function_name', [priority],
	[accepted_args] );

  • action_hook : The name of the hook provided by WordPress.
  • action_function_name : The name of the function you want to use to handle
    the event.
  • priority : An optional parameter, which specifies the execution order of functions.
    The default value is 10. If several functions apply to the same filter hook, then
    functions with lower priority numbers will execute first, while the functions with the
    same priority will execute in the order in which they were added.
  • accepted_args : It is optional and specifies how many arguments your function
    can accept. The default value is 1 and is used for hooks that pass more than
    one argument.

The following table presents example action hooks provided by WordPress.

Just as with filters, you can use the remove_action() function to remove currently
registered actions.

Practical filters and actions examples

Since understanding the power of filters and actions is very important for conquering
WordPress plugin development, we will now examine a few more simple examples of
their usage.

Upper case titles

The hook function can be any registered function. In this case, we will pass the title of the
post to strtoupper making all titles appear in upper case.


	add_filter('the_title', strtoupper);

Mailing list

Actions provide a very powerful mechanism for automating tasks. Here is how to send a
notification to a mailing list whenever there is an update on your blog.


	function mailing_list($post_ID)
	{
		$list = 'john@somesite.com,becky@somesite.com';
		mail($list, 'My Blog Update',
		'My blog has just been updated: '.get_settings('home'));
	}
	// Send notification with every new post and comment
	add_action('publish_post', 'mailing_list');
	add_action('comment_post', 'mailing_list');

Changing core WordPress functionality

Sometimes you may not be satisfied with the default WordPress functionalities. You may be
tempted to modify the WordPress source code, but you should never do that. One of the
main reason is that when you upgrade to a new version of WordPress the upgrade process
could overwrite your changes.

Instead, try whenever possible to write a plugin and use actions and filters to change the
desired functionality.

Let’s say we want to change WordPress post excerpt handling. WordPress uses the
wp_trim_excerpt() function with the get_the_excerpt filter responsible for
processing the post excerpt. No problem, let’s replace it with our own function, using
the WordPress function as a starting point.


	/* Create excerpt with 70 words and preserved HTML tags */
	function my_wp_trim_excerpt($text)
	{
		if ( '' == $text )
		{
			$text = get_the_content('');
			$text = apply_filters('the_content', $text);
			$text = str_replace(']]>', ']]>', $text);
			$excerpt_length = 70;
			$words = explode(' ', $text, $excerpt_length + 1);
			if (count($words) > $excerpt_length)
			{
				array_pop($words);
				array_push($words, '[...]');
				$text = implode(' ', $words);
			}
		}
		return $text;
	}
	// remove WordPress default excerpt filter
	remove_filter('get_the_excerpt', 'wp_trim_excerpt');
	// Add our custom filter with low priority
	add_filter('get_the_excerpt', my_wp_trim_excerpt, 20);

These were just a few practical examples. You can do almost anything that crosses your mind
using action and filter hooks in WordPress.


	Sometimes, you can achieve the same result by using either the action or the
	filter hook.
	For example, if you want to change the text of the post you can use publish_
	post action hook to change the post as it is being saved to the database.
	Alternatively, you can use the_content filter to change the text of the post as
	it is displayed in the browser window.
	Although the result is the same, we accomplish the goal in diff erent ways. In the
	first case, when using the action hook, the post itself will remain permanently
	changed, whereas using the filter hook will change the text every time it is
	displayed. You will want to use the functionality more suitable for your needs.
	
	Quick reference
	add_filter ('filter_hook', 'filter_function_name',
	[priority], [accepted_args]): This is used to hook our function to
	the given filter
	add_action ('action_hook', 'action_function_name',
	[priority], [accepted_args]): This is used to hook our function to the
	given action
	remove_filter() and remove_action(): This is used to remove already
	assigned filters and actions
	the_content : This is a popular filter for the post content. (do not confuse
	with the_content() function, which is a template tag to display the content
	of a post in the theme)
	WordPress Filter Reference: http://codex.wordpress.org/Plugin_
	API/Filter_Reference
	WordPress Action Reference : http://codex.wordpress.org/Plugin_
	API/Action_Reference

Have a go Hero

Our filter function now controls the behaviour of a Digg link. Try these exercises:

  • Place a Digg link before the post content by prepending the output of our function
    to the content
  • Add the current date to your page title in the browser window by using the
    wp_title filter and the date() PHP function
  • Capitalize the first lett er of the users’ comments in case they forgot to do so. Use the
    comment_text filter and the ucfirst() PHP function

Comments

comments

Pages: 1 2 3 4 5

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*