Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

182 PART III • Using Plugins with WordPress


The usual way you generate WordPress plugins relies on creating functions and then applying
them to action and filter hooks. By inserting your function where you need it to be, perhaps
when wp_head or the comments are getting loaded, you can trigger your plugin code at the
appropriate time.

The following subsections describe three ways you can write and work with plugins, starting
with the ever-important hooks.

USING HOOKS
Remember the action hooks from the previous chapter, “Advanced Theme Usage”? Action
hooks are triggered by specific events when a WordPress site is running, such as publishing a
post, which would be the publish_post hook. A second type of hooks, filter hooks, on the
other hand, are functions that WordPress passes data through, so you’d use them to do stuff
with the data. Useful filter hooks include the_excerpt and the_title. You ought to
recognize them from the template tags.

Hooks come in handy for plugins as well — not just for themes. Thanks to hooks, you can add
your cool plugin functionality to the appropriate part of WordPress, such as wp_head or
wp_footer. The web statistics example in Chapter 6, in which you added a function in the
theme’s functions.php template file and then added it to the wp_footer hook using add_
action(), is very much the way a plugin might work.

Often, you’ll end up writing a function in your plugin, and then you’ll add it to one of the
hooks. This is how add_action() works:

add_action( $hook_name, $function_name, $priority, $parameters );

The 'hook_name' is of course the name of the hook to which you want to add the action.
What happens is that WordPress, when encountering that hook when running the code, will
check to see if there are any added functions registered for the hook. If there are, the function
will run; if not, it won’t. And the function is, of course, the one you’ve defined in
'function_name'.

For example, the following code snippet would cause the 'smashingshortcode' function
to run when wp_head() is executed:

add_action( 'wp_head', 'smashingshortcode' );

$priority and $parameters are optional integers. The first, $priority, is the priority
argument (which defaults to 10), used to sort actions when there are several added to a
specific action hook. The lower the number is, the earlier the function will be executed, so if
you need to make sure that something happens before or after something else, this is where
you control that. $parameters, on the other hand, is the number of arguments your
function can accept (defaulting to 1). If you need the function to handle more than one
argument, you can set it by entering another number here.
Free download pdf