The Complete Guide to WordPress Custom Hooks

WordPress hooks

Have you wondered how large WordPress plugins like WooCommerce create large communities that develop dozens of third-party addon plugins and an entirely new WordPress plugin ecosystem?

One of the core concepts that help make these plugins a great success is the ability to easily extend their core functions allowing developers to creatively add their new custom functions without breaking the core.

This programming approach gives developers the flexibility that is necessary for further development and customization.

Consequently, several other useful addon products are created based on the plugin’s core without writing too much code and in sync with the plugin coding standards.

WordPress development is generally based on hooks and filters; the ability to create custom hooks makes WordPress highly extensible.

All the large plugins rely on using custom hooks that third-party developers can extend and build more addon products.

For instance, WooCommerce makes use of several action hooks and filters to allow developers to tap into the core functions like the cart, checkout, templates, add to cart, and so on. You can check out the WooCommerce hooks reference to learn more.

The two main WordPress core functions that help in the application of custom hooks are do_action() and apply_filters() for actions and filters respectively.

If you do not understand how WordPress hooks work, let me begin with a brief explanation.

WordPress Hooks

WordPress development uses hooks and filters to customize the functions of the core without altering the core functions.

Action and filter hooks are designed to help theme and plugin developers add their unique code to the WordPress core during specific events like loading the header, saving a post, initializing, etc.

They are normally called hooks because they allow you to hook into the WordPress core and add your unique piece of code so that it is executed along with the WordPress core code at the specified event.

Actions and filters are the two types of hooks that make it possible to modify the WordPress core and create unique functionality in plugins and themes. It helps to first learn the difference between Actions and Filters before you can start creating them.

Creating WordPress Hook

A WordPress hook comprises two parts; the definition of the hook and the function that is executed by the hook. For the action hook, we use the add_action() function to define the hook and then add a callback function to make it complete.

In a simple example; when we want to output something in the header of the site; we can hook on wp_header and add the code that we want to add to the header to the callback function.

add_action( ‘wp_header’ , ‘callback_function’)

The same applies when creating a filter hook but we use add_filter() instead of add_action(). We can create a filter for the excerpt to trim the number of words by hooking to the excerpt_length and adding a callback function that has the code that trims the excerpt.

add_filter( 'excerpt_length', ‘callback_function’);

The callback functions are independent PHP functions that are defined within the same context where the action or filter hook as been added so that they are executed together. The complete code will look as shown below :

//action hook 
add_action( ‘wp_header’ , ‘callback_function_example’);

//callback function 
function callback_function_example(){

     //print hello world to the WordPress header

     echo "Hello  World";

}

At this point, it seems like the filter and action hooks are doing the same thing, but they are very different. So let us look at the differences between the action hooks and filter hooks to understand in-depth how to use either.

Difference between Actions and Filters

Action hooks let the user add the code at specific execution points of WordPress and have a callback function that adds the code. Ideally, action hooks are designed to inject code to the WordPress core during specific WordPress loading sequence stages.

Action Hooks

Actions can have diverse functionality like adding an output to the front end, adding a function when a post is saved, and much more.

The following is an example of an action that hooks to the footer and has a call-back function that prints a simple message on the footer.

//Action hook

add_action( ‘wp_footer' , ‘call_back_function_footer_example’);

//Callback function

function call_back_function_footer_example(){

        echo “Example of an action hook to the footer”;

}

This action hook can be added to the filefunctions.php in your theme or can be added to the plugin code.

Filter Hooks

Filters are designed to help the user change the data as WordPress is executing or displaying. As the name suggests; it filters the data, modifies and returns it.

The following is an example of a filter that we use to apply to the_content() function, filter it then modify it by adding new content and then return the content.

//Filter hook

add_filter('the_content', 'add_new_content_callback_function);

//Callback function

function add_new_content_callback_function(){

$newcontent = "This is an example of a filter";

$fullcontent = $content . $newcontent;

return $fullcontent;

}

This filter hook can be added to the functions.php file in your theme or can be added to the plugin code.

After mastering the action and filter hooks we now need to create custom hooks that can be used across the WordPress application to extend functionality. Now let us look at how to use the two custom hooks do_action and apply_filters.

Custom Hooks do_action and apply_filters

Creating your custom hooks is easy and gives you the flexibility to need when building a robust plugin.

The two ways you can utilize the custom hooks are by using the do_action function and the apply_filters() function.

Let us begin with the do_action function :

Do Action

As we mentioned above; action hooks enable you to hook to a specific event and when fired the callback function is executed.

There are tons of action events that occur during the WordPress life-cycle like the init, wp_header, wp_footer, admin etc.

You can check out the WordPress actions reference to learn more.

To make action hooks more flexible the do_action function allows you to create your custom hook and later use the do_action() to execute this hook. Maybe this sounds too complex, but let me illustrate with a simple example:

Suppose we want to show some text below the header of a post; a practical example is adding an advertisement code below the title of every single post.

We can create our custom hook and use do_action () to show the ad content below the header of every post.

Steps

The three steps are as follows:

#1) Create Hook – Create the action hook to add the ad content.

#2) Callback Function – Create the callback function and add the text to display.

#3) Do Action – Use do_action() to call the action hook in the theme – single.php file.

It is worth noting that this code can be added to both the theme functions.php file or can be used in a plugin. At this point; I prefer to use add the code in the functions.php but will illustrate how to add in a plugin later.

Creating the Custom Action Hook

To create the action hook use the add_action() function and the first parameter assign a unique name that will be used later to call the hook in the do_action().

For our example, our hook name is ‘display_ad_below_title_hook’. You should make sure that this name is unique to avoid collision with hooks from other plugins or themes.

Our callback function name will be ‘post_title_ad_hook_callback’ – it is our second parameter in the add_action() function as shown below :

add_action( 'display_ad_below_title_hook', 'post_title_ad_hook_callback'  );

With this code, we have now created the custom action hook and should now move to the next step of adding the content we want to display in the callback function.

Create the Callback Function

We should now create the callback function that we added in the action above and add the content as follows:

function post_title_ad_hook_callback(){

echo "This is an example of Ad Content";

}

We have just created the function and added simple text that we presume is the ad content that we want to display below the title.

You can add this code to the functions.php file in your theme to test the custom hook you created with do_action.

 

Now it is time to showcase our action hook using the do_action(). Please remember, you can use this function across all your theme or plugin files where you want to run the action hook.

Execute the Do Action

Now it is time to call our action hook and to display the example ad content. Open your theme and locate the single.php file and below the title, code add the do_action call as follows:

do_action( 'display_ad_below_title_hook');

 

As you can see in this example we have successfully created the action hook and executed it using the do_action().

This can be repeated throughout the theme by calling the same do_action() hook in several places in the theme where we want the action to be executed.

When added to the post as shown in the image above you should see the results shown below:

 

Apply Filters

This is the second function that is used with the filter hooks. Apply_filters is an important function that is designed to call the functions that are attached to a specific filter hook. It is important to note that this filter hook is written as apply_filters NOT apply filter. This is a common mistake that will make it not work!

The apply_filters() takes two parameters – the first is the tag which is a string and the second is the value. The following is a basic illustration of apply_filters().

Steps

The three steps are as follows:

#1) Create hook – Create the filter hook

#2) Callback function – Create the callback function

#3) Apply_filters – Use apply_filters() to callback functions that have been added to a filter hook.

Creating the Custom Filter Hook and Callback Function

To create a filter hook you should give it the name and the name of the callback function as shown in the code below :

add_filter( 'filter_name', 'your_callback_function_name' );

Suppose we are working on a custom sidebar menu and want to use a filter to modify the data, we can start by creating the filter and the callback function that shows the custom sidebar menu :

add_filter('the_sidebar_menu', 'display_sidebar_menu'); 

// The filter callback function
function  display_sidebar_menu($menu){

// (maybe) modify $menu or return 
return $string;

}

 

We can now create the array with our custom menu items as shown below :

//Data of a custom sidebar menu
$custom_sidebar_menu = array( "Page One", "Page Two", "Page Three"," Page Four" );

Apply Filters

Now we can apply filters and display the sidebar menu using a for each loop

$sidebar_menu = apply_filters('the_sidebar_menu', $custom_sidebar_menu);

foreach($sidebar_menu as $menu_item){

echo $menu_item . "<br>";

}

 

You can now see the menu displayed on the sidebar as shown in the image below :

 

To illustrate the power of the apply_filters function we can modify the callback function further to filter the custom menu array and display the menu item in lowercase. In this case, we should modify the callback function as shown below :

function display_sidebar_menu($menu){

$menu = array_map('strtolower', $menu);

return $menu;

}

Final Thoughts

Do_action and apply_filters are very useful WordPress functions that help developers to use custom hooks to extend and improve the core functionality of WordPress with custom features that are specific to a plugin or theme.

It is my hope that this tutorial has helped you understand how to use these two functions and the differences between action and filter hooks in WordPress. If you would like more assistance from a WordPress developer, do not hesitate to get in touch with me.

Similar Articles

 

Comments are closed.