Adding Custom Hooks in WordPress: Custom Actions

One of the cornerstones of building custom solutions in WordPress is having an understanding of hooks. In and of themselves, they aren’t terribly difficult to understand, and we’ll be covering a short primer on them in this tutorial.

But if you’re looking to get into more advanced WordPress development, it’s worth knowing how to implement your own hooks, as well.

In this two-part series, we’re going to review the WordPress hook system and how it’s implemented, and we’re going to take a look at how to define both our own actions and filters.

Getting Started

Before getting started, this tutorial assumes that you have a local development environment set up that includes the latest copy of WordPress. At the time of this writing, this is WordPress 4.5.2. 

If you need guidance on setting up your development environment, please see this tutorial. It will provide you with everything you need to know to get set up with a web server, a copy of PHP, a database, and WordPress.

If you’re looking for even more, then the series in which that tutorial is included provides even more information such as how to install WordPress, walkthroughs of themes and plugins, and more.

But in this tutorial, we’re focusing on hooks and actions. So once you’re all set up, let’s get started.

What Are Hooks?

Before taking a close look at WordPress hooks, it’s worth understanding the event-driven design pattern (which is also referred to as an event-driven architecture). 

If you’ve worked with existing WordPress hooks or with front-end web development or with JavaScript in any capacity, you’re likely familiar with this pattern even if you didn’t know it had an official name. 

Regardless, this is how it’s defined in Wikipedia:

Event-driven architecture (EDA), also known as message-driven architecture, is a software architecture pattern promoting the production, detection, consumption of, and reaction to events.

If you’re just now getting started with design patterns or development, this may sound complicated, but another way to think of it is like this:

  • The software has certain points in which it broadcasts a message that something has happened.
  • We, as developers, are able to write code that listens for this message and then respond to it with custom code.

Notice that the definition talks about the production of events, as well. When we move into talking about defining our own hooks, we’ll be revisiting this topic. For now, let’s look at two events that are common in web development.

Using JavaScript

First, imagine you’re working in front-end development. You have a button with the ID attribute of command-button, and when the user clicks on it, you want to display an alert dialog.

Using jQuery, you can implement this functionality like this:

The comments in the code above should explain exactly what’s happening. In short, the browser raises an event when the user clicks on a button. When that happens, our code listens for the event and then responds by displaying a dialog.

Of course, other libraries, frameworks, or vanilla JavaScript afford this same functionality. The purpose of showing this within jQuery is because it’s one of the most common JavaScript libraries, and because it’s also what’s bundled with WordPress.

Using WordPress

The implementation of this pattern doesn’t necessarily look the same across all programming languages or paradigms. This often depends on the APIs that the framework, foundation, or application provide.

In WordPress, registering our own code with an event that fires is a bit different. For example, let’s say that you’re working with the administration pages in WordPress and you want to add a new submenu item to the Settings menu. We’ll call it Tuts+ Options.

To do this, we’d add the following code to our functions.php file or our plugin or whatever type of project on which we’re focused:

You can visit the Codex to read more about the admin_menu hook as well as the add_submenu_page function.

This code doesn’t add any new functionality to the menu, but it’s meant to demonstrate that WordPress provides an admin_menu event, much like a web browser provides a click event. We’re then able to inject our own code by defining a function and have it fire whenever that event is raised.

These are two practical examples of the event-driven design pattern being both implemented and used.

Understanding WordPress Actions

Now that we’ve had a short primer on the event-driven design pattern and seen two implementations of the pattern, let’s look specifically at WordPress actions. We’ll review what’s available and how we can implement our own.

Setting Up Our File

For the purposes of the code in this tutorial, we’re going to be using the default twentysixteen theme that ships with WordPress.

In the root of the theme directory, create a file called tutsplus-actions.php. Then, in functions.php, add the following line of code:

This instructs the theme to load the file we’ve defined. The reason we want to do this is so that we can keep our code out of the core of the theme, and so that we can easily remove the code by deleting the include_once statement above.

A Brief Definition of Actions

In WordPress, hooks fall into one of two categories: actions or filters. Actions are points in the WordPress lifecycle that allow you to add, remove, or modify certain functionality. Filters, on the other hand, are points in the WordPress lifecycle in which you can add, remove, or modify data.

In short, actions are intended to work with functionality, and filters are meant to work with data. We’ll be focusing on filters more in the second part of this series.

One thing I want to point out is that if you opt to research actions and filters more after reading this series of tutorials (which I encourage), you may find others referring to them more generally as hooks.

Though this is technically correct, it’s more pragmatic and it’s clearer to discuss the type of hook you’re working with whenever you’re writing, presenting, or discussing the topic with someone else. 

This is because actions are meant to afford one type of functionality, and filters are meant to afford another type of functionality.

Working With Actions

Though we’ve already looked at a specific example of an action in some example code above, let’s take a look at a more complete and more practical example.

Out of the box, WordPress offers two types of posts: Posts (for regular blog posts) and Pages (for static content or content that will rarely change). For a standard blog platform, this type of content is arguably all you need. But WordPress matured into a CMS years ago.

And one of the features that makes WordPress extensible is the ability to introduce our own post types. WordPress calls these custom post types, and they are great when we need to create a type of content that needs its own type of attributes and that needs to be named something more specific than „posts“ or „pages“.

In order to create our own custom post type, we’ll need to do two things:

  1. define a function that hooks into the init hook as provided by WordPress
  2. register our post type with one of the provided API functions

Registering Our Action

To register our action, we’ll make use of the add_action function provided by the WordPress API. This tells WordPress that we’re introducing an action and that it needs to fire the function identified by the name we’ve provided in the call to the function.

Our code should look like this:

In the code above, we’re registering a function with the init hook that exists in WordPress. This hook fires early in the WordPress lifecycle and is a good time in which to register a custom post type.

Next, we need to define the function.

The key to understanding the signature of this function is simple: We’ve named it tutsplus_register_post_type as that’s the second argument we’ve passed into the add_action call.

This literally instructs WordPress to do the following: During init, make a call to the tutsplus_register_post_type function.

So far, so good. We’ve not really hit anything complicated, and if you refresh your administration screen of WordPress, then you will see it’s still functioning although it isn’t doing anything new.

Let’s change that.

Creating a Custom Post Type

Now that we have the skeleton code for adding our own action, let’s actually make something happen. Specifically, let’s create a custom post type called time_traveler that includes a title, an editor, an excerpt, and nothing else.

To do this, we need to review the register_post_type function in the Codex. The documentation gives a solid explanation for all of the arguments that the function can accept, but we’re only going to be using a subset of them for our custom post type.

Specifically, we’re going to use the following:

  • label
  • labels
  • description
  • public
  • show_ui
  • supports

We’ll rely on the rest of the functionality to be provided by the WordPress default values. The arguments will look like this:

And the final, full version of the code for registering the post type will look like this:

When you refresh the administration area of your WordPress installation, there should be a new menu item directly under Comments that reads Time Travelers.

When you click on Add New, you should see a place for a title (or the Traveler’s name), the editor (for the traveler’s information), and an excerpt (perhaps for some notes about the traveler). You should also see a single meta box for publishing the information.

Adding a Time Traveler custom post type

Of course, the above code shows us how to take advantage of existing actions to define a custom post type. But what if we want to create our own actions?

Defining Custom Actions

When it comes to creating our own actions, there are three things that we need to do. At the most fundamental level, we need to do the following:

  1. define the hook
  2. give functionality to the hook
  3. allow developers to call the hook

The simplest example I can give for this is in the following code:

Feel free to add this example code to tutsplus-actions.php so that you continue to tweak and explore the code after this tutorial.

After that, we can call our function tutsplus_action anywhere in our code. Let’s say, for example, we wanted to display it at the top of the administration area. If that’s what we wanted to do, then we could add the following code:

If you refresh your dashboard, you’ll see „This is a custom action hook“ displaying at the top of your dashboard. 

Note that I do not recommend hooking into admin_notices unless you’re specifically planning to notify the user of a success, warning, or error message. I’m using it here specifically as a way to demonstrate our custom hook.

Revisiting Our Post Type

Let’s say we wanted to create a custom post type function that allows us to pass the singular and plural name of the post type into a function through the use of an action hook.

How might we go about doing that? Using what we’ve seen above, we know the first thing that we need to do is to create a custom function that will call an action. So let’s do that now:

Next, we need to do something that’s going to seem a little counterintuitive. Since we want our custom functionality to fire within the context of the init hook, we need to make sure that our hook is fired during the init action. 

To do this, we hook our custom hook to the init hook:

Note in the code above we’re specifying two additional parameters for do_action. The first parameter is 10, which indicates the priority in which this hook will fire. 

This can be any number where the higher the number, the lower down the list of priorities it will fire. The second parameter is how many arguments the custom hook will accept. In our case, there is one for the singular version of the post type, and there is one for the plural version of the post type.

After that, we need to give functionality to that hook. Here, we’ll refactor the code for registering a post type so that it accepts two arguments, and those two arguments will be used in the array passed to WordPress’s register_post_type function.

Notice here that we’ve also removed this function from being added to a particular hook. Instead, we’ll call it from within the definition of a function that’s hooked to our custom action.

In the code above, we’re able to make a call to the function responsible for registering the custom post type, all the while passing it our own arguments so that we can add a little bit of custom functionality to the code.

Conclusion

Defining custom hooks isn’t complicated, and it also lends a lot of power and flexibility to us as developers. Arguably, the most confusing thing about the code above is how we’re defining a hook within the context of another hook (that is, we’re defining tutsplus_register_custom_post_type within init).

I’ve opted to give this as a final example because there are times in which you may want to register a custom hook and it needs to fire before a pre-existing hook is completed.

Registering a hook to stand on its own is easy: You simply don’t hook it to a pre-existing hook, and you make a basic function call as we saw with the code hooked to admin_notices.

In the next post in this series, we’ll take a look at filters and what they can do for us in terms of modifying data. We’ll also look at how to define our own filters so that we’re able to introduce custom functionality much as we’ve done in this tutorial.

Until the next article is published, if you’re looking for other utilities to help you build out your growing set of tools for WordPress or for code to study and become more well-versed in WordPress, don’t forget to see what we have available in Envato Market.

Remember, you can catch all of my courses and tutorials on my profile page, and you can follow me on my blog and/or Twitter at @tommcfarlin where I talk about various software development practices and how we can employ them in WordPress.

Please don’t hesitate to leave any questions or comments in the feed below, and I’ll aim to respond to each of them.

Related Resources

from Envato Tuts+ Code – WordPress http://ift.tt/2aAGZCw

Schreibe einen Kommentar

Bitte logge dich mit einer dieser Methoden ein, um deinen Kommentar zu veröffentlichen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s