What is WordPress Hook? How to use Hooks in WordPress Development With Examples?

Hooks are functions in WordPress that lets the developer or WordPress users to add their own code or modify their code in WordPress core files, plugins, and themes without touching the core files. 

According to codex hooks is described as “Hooks are provided by WordPress to allow your plugin to ‘hook into’ the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion.” Hooks can be used in both plugin and theme files to add and create custom functions or to edit and remove functions that are already present in your theme code.

Instead of making changes to the WordPress core files, hooks helps the developers to change the functions of the WordPress core files using the custom coding. So that the WordPress core files, theme or the plugins remain on its own stability. And also whenever you update your WordPress, the changes made will not be lost. Hooks will be normally written in the child themes function.php file.

Hooks are normally categorized into two types. They are:

  • Actions
  • Filters

What is the Need of WordPress Hooks?

If you are not aware of making changes, it is really a bad idea to make changes to the WordPress core files. Once your WordPress is updated, then your changes to the code have to rewritten again. The same happens for plugins and themes. So, you have to keep track of all the updates and make changes each and every time. 

And at a certain point in time, you might even not know what changes are been made, it is difficult for future maintenance too.  In order to avoid such situations, the hook concept comes into existence. Using hooks you can offset the risks of changing core functionality. It is a key to WordPress extensibility and for the plugins and themes. It saves your time as well as making you work tension free. 

Action Hook in WordPress

Action hook is a function that triggers when a certain event occurs in WordPress. They are called when some action takes places like loading a page, a user logging in, or a custom action that you specify in your plugin or theme. It allows you to take an action and make changes to the code of your website. You will be able to add your action hooks using add_action() function. Any functions that hook to action will run at the specific point in the code. Action hooks may or may not pass any argument through their hooked functions. The syntax for action hook is 

add_action($hook_name, $your_function_name, $priority, $accepted_args );

Function your_function_name()

{

// your code

The required parameters are the hook name and your function name. Hook name is the name of the action hook provided by WordPress, that specifies what event your function should be related with. Your function name is the name of the function that you want to be executed following the event specified by a hook name. 

The priority is an optional parameter. It is an integer value and determines the priority of order for functions, that is tied to a specific hook. The lowest priority runs earlier and the highest priority runs later. The accepted args parameter is used to pass multiple arguments.

Example 

Let’s take a scenario as “When Dave is done with work, he must go to the store to get cat food. When the cat meows, Dave feeds her”

Here the action Dave is done with work, he must go to the store to get cat food. 

This can be done, by hooking onto an action.  

<?php

// Let’s get the cat some food

// This enables Dave to go the store after work 

add_action(‘after_work’, ‘get_cat_food’, 10, 2);

// This defines how does it

Function get_cat_food($dave_has_wallet, $cat_is_hungry) {

// Dave only goes if he has the cash and the cat needs food

if($dave_has_wallet && $cat_is_hungry) {

Echo ‘Dave is on his way to the store’;

}

?>

How this Action Performs? 

Here in this example, we have used an action for dave that states when he goes to the store (after_work)hook and what to do when after_work happens get_cat_food function. We can even use the after_work hook for other actions such as drive_home or feed_cat.

In this example we have set a priority as 10, to ensure get_cat_food happens before drive_home. The number 2 represents the action refers to how many arguments the action will take. The default is 1, and in most cases, it’s not necessary. In our example we have 2 arguments ($dave_has_wallet, $cat_is_hungry). 

do_action() function

It is used to execute functions hooked on to a specific action hook. You can hook any functions to that action will the run at that point in the code. You can even use action hook by do_action() function. 

The syntax for do_action() function is

do_action($hook_name, $arguments);

do_action(‘after_work’, $dave_has_wallet=true, $cat_is_hungry=true);

In this above code, it tells the WordPress to use the hook named after_work, and then run the actions that are attached to the hook, and pass the arguments.

If there is a hook with no arguments, you might simply state it as do_action(‘after_work’); Just by stating this, it will run all the actions that use the after_work hook in the order of priority.

Example of add_action and do_action

Function page_who_is_perfoming_action($a,$b)

{

Echo ‘<code>’;

print_r($a); // ‘print_r ’ is the array data inside the first argument

Echo ‘</code>’;

Echo ‘<br/>’.$b; // echo line break and value of second argument

}

add_action(‘page_i_am_performing_action’, ‘page_who_is _performing action’, 10, 2);

// Define the arguments for the action hook

$a=array(

‘eye patch’=> ‘yes’,

‘parrot’=> true,

‘wooden leg’=> 1

);

$b= (‘and action states: “I had my dinner with dave.”’, ‘textdomain’);

// Executes the action hook named ‘i_am_performing_action’

do_action(‘page_i_am_performing_action’, $a, $b);

The output is

array(

[‘eye patch’]=$gt; ‘yes’

[‘parrot]’=$gt; true

[‘wooden leg’]=$gt;  1

)

and action states:  “I had my dinner with Dave.”

The above example is for defining the add action and do action function. 

Filter hook in WordPress

Filter hooks are functions when you need to manage, return, or intercept data before rendering it to the browser or saving data from the browser to the database. It sits between the database and browser as WordPress generates pages and also sits between the browser and database as WordPress adds new posts and comments to the database. In simple words, it helps to work on the data before it is submitted for publishing. 

A filter is usually intended to receive a value, and then return the modified version of that value.  Filter hooks are called throughout the code using add_filter() function. The syntax for filter hook is the same as that of the action hook. 

add_filter($hook_name, $your_function_name, $priority, $accepted_args );

Every parameter represents the same as that of the action hook.

Example 

With the same above example scenario let’s take “When the cat meows, Dave feeds her”

We will be able to change what the cat does by hooking onto a filter. We can use add_filter to modify the behavior or functionality.

// Giving the cat a speech
add_filter(‘cat_meows’, ‘cat_can_speak’);

Function cat_can_speak($meow) {

$meow= “I am hungry now”;

Return $meow; }

How this filter performs?

add_filter() is for adding the new custom filter. We can only use add_filter in the above example once we know that the filter hook exists (cat_meows). Next, the apply_filters() function is that how you hook in the filter function. 

Behind, our themes original filter might look like

Echo apply_filters(‘cat_meows’, “meow!”);

The above code tells the WordPress to create a hook called ‘cat_meows’, apply to any filters that are attached to this hook, and it passes those filters along with the string  “meows”. Then what happens is that the apply_filters() function will just return the string “meow!”.

Example of add filter and apply a filter

// Filter call

$value = apply_filters( ‘hook’, $value, $arg2, $arg3 );
// Accepting zero/one arguments.
function example_callback() {
…………  

return ‘some value’;
}

add_filter( 'hook', 'example_callback' ); // Where $priority is default 10, $accepted_args is default 1
// Accepting two arguments (three possible).
function example_callback( $value, $arg2 ) {

…………….

return $maybe_modified_value;
}
add_filter( 'hook', 'example_callback', 10, 2 ); // Where $priority is 10, $accepted_args is 2

Removing actions or filters in WordPress 

Removing actions or filters in WordPress is very easy. When you think you no longer required the hook, you can just call it by remove_action() function or remove_filter()function. 

For example, there is a plugin registering an action and filter

add_action(‘save_post’, ‘my_action_callback’);

add_filter(‘the_content’, ‘my_filter_callback’); 

You can easily remove it by adding the code

remove_action(‘save_post’, ‘my_action_callback’);

remove_filter(‘the_content’, ‘my_filter_callback’); 

Advantages of hooks:

  • The basic advantage of hooks is that it helps in customizing the WordPress core codes
  • Once you understand the clear concept, it helps to make even complex changes easily
  • A new plugin development is made very easy as you can try and debug
  • If you know the entire concept of creating functions, you can easily develop plugins and use those plugins universally for any themes.
  • For theme development, one can create child themes and try with hooks without affecting the parent theme
  • You can reuse your changes and even debug
  • You can even enable and disable your changes by commenting out single blocks of code in your functions.php
  • Since you don’t have to makes changes in the WordPress core code, even if your WordPress is updated, your changes are not lost.

Conclusion

WordPress hooks play an important and powerful tool for WordPress developers. Just by knowing the hook concept, any WordPress users can modify the core functionality without touching any files. Hooks are mainly used to modify the existing WordPress code to customize your website. 

Though hooks are having a lot of advantages, one should make sure that each hook is unique. You can even assign the priority to the hooks for the execution as per your requirements. Hope you got an idea about hooks. If you have any queries please feel free to comment to us. You can subscribe to us at Facebook and Twitter.

Leave a Comment

%d