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.
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:
- (function( $ ) {
- 'use strict';
- // jQuery's DOM-ready event-handler
- $(function() {
- /**
- * Listen for the 'click' event on the button identified
- * with the 'command-button' ID attribute.
- *
- * When the user clicks on it, display an alert dialog.
- */
- $( '#command-button' ).bind( 'click', function( evt ) {
- alert( 'You clicked the button.' );
- });
- });
- })( jQuery );
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:
- <?php
- add_action( 'admin_menu', 'tutsplus_admin_menu' );
- /**
- * Adds a 'Tuts+ Options' submenu to the 'Settings'
- * menu in the WordPress administration menu.
- */
- function tutsplus_admin_menu() {
- add_submenu_page(
- 'options-general.php',
- 'tutsplus-admin-menu',
- 'Tuts+ Options',
- 'manage_options',
- 'tutsplus-admin-menu-top',
- 'tutsplus_admin_options'
- );
- }
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:
- <?php
- include_once( 'tutsplus-actions.php' );
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:
- define a function that hooks into the init hook as provided by WordPress
- register our post type with one of the provided API functions
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:
- <?php
- add_action( 'init', 'tutsplus_register_post_type' );
Next, we need to define the function.
- <?php
- function tutsplus_register_post_type() {
- }
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:
labellabelsdescriptionpublicshow_uisupports
- <?php
- $args = array(
- 'label' => 'Time Travelers',
- 'labels' => array(
- 'name' => 'Time Travelers',
- 'singular_name' => 'Time Traveler',
- 'add_new_item' => 'Add New Traveler',
- 'edit_item' => 'Edit Traveler',
- 'new_item' => 'New Traveler',
- 'view_item' => 'View Traveler',
- 'search_items' => 'Search Travelers',
- 'not_found' => 'No Travelers',
- ),
- 'description' => 'A post type used to provide information on Time Travelers.',
- 'public' => true,
- 'show_ui' => true,
- 'supports' => array(
- 'title',
- 'editor',
- 'excerpt',
- ),
- );
- <?php
- add_action( 'init', 'tutsplus_register_post_type' );
- function tutsplus_register_post_type() {
- $args = array(
- 'label' => 'Time Travelers',
- 'labels' => array(
- 'name' => 'Time Travelers',
- 'singular_name' => 'Time Traveler',
- 'add_new_item' => 'Add New Traveler',
- 'edit_item' => 'Edit Traveler',
- 'new_item' => 'New Traveler',
- 'view_item' => 'View Traveler',
- 'search_items' => 'Search Travelers',
- 'not_found' => 'No Travelers',
- ),
- 'description' => 'A post type used to provide information on Time Travelers.',
- 'public' => true,
- 'show_ui' => true,
- 'supports' => array(
- 'title',
- 'editor',
- 'excerpt',
- ),
- );
- register_post_type( 'time_traveler', $args );
- }
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.
![]() |
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:
- define the hook
- give functionality to the hook
- allow developers to call the hook
- <?php
- /**
- * Define the action and give functionality to the action.
- */
- function tutsplus_action() {
- do_action( 'tutsplus_action' );
- }
- /**
- * Register the action with WordPress.
- */
- add_action( 'tutsplus_action', 'tutsplus_action_example' );
- function tutsplus_action_example() {
- echo 'This is a custom action hook.';
- }
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:
- <?php
- add_action( 'admin_notices', 'tutsplus_admin_notice' );
- function tutsplus_admin_notice() {
- tutsplus_action();
- }
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:
- <?php
- function tutsplus_register_custom_post_type() {
- // Set the action at priority of 10 and note that it accepts 2 arguments.
- do_action( 'tutsplus_register_custom_post_type', 10, 2 );
- }
To do this, we hook our custom hook to the init hook:
- <?php
- add_action( 'init', 'tutsplus_register_custom_post_type' );
- function tutsplus_register_custom_post_type() {
- // Set the action at priority of 10 and note that it accepts 2 arguments.
- do_action( 'tutsplus_register_custom_post_type', 10, 2 );
- }
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.
- <?php
- function tutsplus_register_post_type( $singular, $plural ) {
- $args = array(
- 'label' => $plural,
- 'labels' => array(
- 'name' => $plural,
- 'singular_name' => $singular,
- 'add_new_item' => 'Add New Traveler',
- 'edit_item' => 'Edit Traveler',
- 'new_item' => 'New Traveler',
- 'view_item' => 'View Traveler',
- 'search_items' => 'Search Travelers',
- 'not_found' => 'No Travelers',
- ),
- 'description' => 'A post type used to provide information on Time Travelers.',
- 'public' => true,
- 'show_ui' => true,
- 'supports' => array(
- 'title',
- 'editor',
- 'excerpt',
- ),
- );
- register_post_type( 'time_traveler', $args );
- }
- <?php
- add_action( 'tutsplus_register_custom_post_type', 'tutsplus_register_time_traveler_type' );
- function tutsplus_register_time_traveler_type() {
- tutsplus_register_post_type( 'Time Traveler', 'Time Travelers' );
- }
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.
Written by Tom McFarlin
If you found this post interesting, follow and support us.
Suggest for you:
Wordpress Basic to Advanced Tutorials
How To Start A Profitable Wordpress Blog Step By Step 2016
How to Make a Wordpress Website 2016

No comments:
Post a Comment