Explaining the hooks in WordPress and their importance to template and plugin developers

WordPress Hooks are considered one of the most important features that help WordPress developers develop their own WordPress themes or plugins, modify the way a template or plugin works, or change the way WordPress itself works.

Hooks are essentially functions that contain code that can perform an action, or filter and modify specific data in WordPress.

In this article, we will explain the concept of hooks in WordPress and learn about their types and how they work. It is worth noting that this topic is considered one of the necessary topics that any developer of WordPress templates or plugins must understand well as part of the WordPress development process.

What are hooks in WordPress?

On any WordPress site, there are three basic elements that work with each other to form and display the site’s pages in their final form: the WordPress core , the WordPress template, and the external plugins activated on the site.

The WordPress core runs the basic functionality of a website, while plugins and themes add more features and functionality to the site and control its appearance, both of which make extensive use of hooks.

The main task that hooks do in WordPress is to allow WordPress developers to modify or add features to the default WordPress features without compromising the core files of WordPress itself.

It allows you to extend WordPress by having it execute your own code, and connect that code at specific points or places to automatically run your custom code.

Core WordPress includes more than 2,200 virtual hooks that allow the developer to specify the exact place where he wants to hook and run his custom code. You can see a list of all these hooks and when they work at the following link

Once you hook your code with a hook you will be able to direct your code to do anything custom on your site. For example, you can use hooks to automatically send an email to all your followers after each article is published on the site.

The Plugin API powers the hooks functionality in WordPress. You can use hooks by calling specific WordPress functions called Hook Functions that are called in certain situations that occur while running WordPress.

Using hook functions, you can compile your code into a function or callback function and link it to any hook.

The callback functions can be used either as regular PHP functions, or as default WordPress functions, or you can write your own custom programming functions depending on what you want to implement on the site. (You can visit the next page in the official WordPress Developer Guide for more instructions on functions in WordPress)

Once you associate the hook with this callback function, it will run everywhere the hook occurs, allowing a WordPress developer to add new features to or modify default WordPress features.

Types of hooks in WordPress

WordPress provides two types of hooks:

  1. Action Hooks that allow a developer to execute a specific task or command at pre-defined points in the WordPress runtime.
  2. Filter hooks that allow you to modify any data processed by WordPress and return this modified data.

In the following paragraphs, we will discuss each of these types and their most important consequences in more detail. But before you, let us explain how hooks work in WordPress in more detail

Knowing that in some cases you can use an action hook or filter to perform the same task and get the same result. So, as a WordPress developer, you have to know when to use one or the other.

How do hooks work in WordPress?

WordPress hooks, as we explained earlier, enable developers to interact with their website or modify it as they want.

We have 3 types of programming functions that work in the hook system:

  1. The hooks themselves, of both types (Action hooks or Filter Hookd), are already present in the WordPress code. By itself, it does not do anything. Rather, it exists only in the code and waits for one of the hook functions to activate it.
  2. Hook functions (Action functions and Filter functions) are used to associate or register hooks with callback functions.
  3. Callback functions that include custom code that the developer wants to execute when the associated hook occurs.

note:

It does not matter the order in which you use these functions in your code. You can first define the callback function and write custom code within it, then register it and associate it with the required hook. But it is better to place them close to each other within the code for easy understanding of their connection to each other.

These functions provide you with the ability to intervene in the process of building website pages and give you more control over what you build. To better understand how hooks work, you can imagine that your website is a building being built, and the hooks themselves are a lever that moves elements back and forth to and from that building.

The items that hooks move or bring into the building are callbacks that contain the custom code you want to execute. These elements (or functions) can help you in the process of building or modifying a home.

We can only carry certain things on specific vectors attached to certain hooks, so action hooks can only be linked to Action Functions like add_action() and remove_action() and Filter hooks can only be linked to Filter Functions like add_filter() and remove_filter() We will explain the task of each of these functions in detail later)

 Action functions do not pass any value to their callbacks and can perform any task, including changing the way the WordPress core works. While filter functions need to pass an argument to their callback function, they are only able to modify the data passed to them by filters and must return the modified values ​​as usable output.

For example, you can modify the text in a post by hooking the callback function to the publish_post action hook and changing the content of the post when it is saved to the database as follows:

// define the callback function to change the text
function change_text_callback() {
// add the code to change text here
}
// hook in to the ‘publish_post’ action with the add_action() function
add_action( ‘publish_post’, ‘change_text_callback’ );

Alternatively, you can register another callback function, this time using the the_content filter hook, in order to modify the content of the article before displaying it in the browser, as follows:

// define the callback function to modify the text
function change_text_callback( $content ) {
// add the code to change text here and then return it
return $filtered_content;
}
// hook in to ‘the_content’ filter with the add_filter() function
add_filter( ‘the_content’, ‘change_text_callback’);

Do things seem confusing and complicated to you? Don’t worry, in the following paragraphs we will explain more about hooks and attach practical examples to explain it better.

Action Hooks in WordPress

Action Hooks in WordPress are defined through the do_action function , which takes the following form:

do_action( ‘action_name’, [optional_arguments] );

whereas:

action_name is a text string that represents the name of the event or action that will occur on the site, and it is usually an expressive name that explains the meaning of this event.

[ optional_arguments] is a field for optional variables or arguments that can be passed to the callback function. If no value is specified for this field, its default value will be empty.

For example the following action hook:

do_action( ‘wp_head’ )

It is a function that represents an action hook through which you can run custom code every time WordPress displays the header of your site. This hook does not have any arguments or parameters.

And the next action hook

do_action( ‘wp_footer’ )

It is a function that represents an action hook through which custom code can be run every time WordPress displays a footer on your site. This hook also does not have any additional arguments or parameters.

The most important functions of procedure hooks

In this paragraph, we explain the most important programming functions that are used with action hooks in WordPress

  • function add_action

The add_action() function is the most widely used action hook function, and is primarily used to bind your callback function
to a specific action hook. This way we tell WordPress to execute the callback function code when this action occurs. Therefore, this function accepts two arguments: the name of the action that you want the code to execute when it occurs, and the callback function that contains this code.

add_action( ‘hook_action_name’, ‘callback_function’);

For example, to execute the wporg_callback() function when the init hook occurs, we write the following code:

add_action( ‘init’, ‘wporg_callback’ );
function wporg_callback() {
// Write here the code you want to execute
}

The add_action () function can also accept two optional additional parameters or arguments, namely priority and number of parameters .

1- Priority: It is a positive integer whose default value is 10. This parameter determines the priority of executing the callback function associated with the hook. The lower the priority value, this means that the function will be run earlier.  

The priority parameter is important when a developer wants to bind multiple callback functions to a hook and wants to avoid getting incorrect results from the order in which these functions are executed. For example, if we associate 3 callback functions with a hook, as follows:

 foo1()  has priority value set to 11

 foo2() is set to priority value 10

 foo3() has priority value set to 9

This means that when the hook occurs, the foo3() function will be run first, then the foo2() function , then the foo1() function . If their priorities are the same, the functions will be run in the order in which they are linked within the code.

2- Number of parameters Accepted args : By default, any callback function associated with the hook through the add_action () function receives only one argument. But sometimes you may need to pass additional arguments to the callback function.

That’s why the add_action () function can accept   additional optional arguments with which you can set the number of arguments you need.

For example, the comment_post hook is executed immediately after WordPress adds a comment to an article in the site’s database. If you do not set the number of arguments parameter for this hook, only one value will be passed to its associated callback function, in this case the comment_ID .

If you want to set an additional parameter that represents a boolean value comment_approved,  which takes the number 1 if the comment is approved and 0 if the comment is rejected because it is marked as spam,  pass the value 2 to the number of hook parameters as follows:

add_action( ‘comment_post’, ‘show_message_function’, 10, 2 );

If you set the number of parameters to 2, this means that you can now pass two values ​​to the response function: comment_ID and comment_approved, so that you can execute specific code in this function only when you verify that the comment is acceptable and not a spam comment, as follows:

function show_message_function( $comment_ID, $comment_approved) {
// check whether a comment is approved with the second parameter
if( 1 === $comment_approved ){
// Write here the code you want to execute only if the comment is acceptable
}
}

You can of course pass as many parameters or arguments as you need and your code, but make sure that both the add_action() function and the callback function have the same number of arguments.

  • Function do_action

 This function, as we explained previously, is used by the WordPress system itself to define all default action hooks in the system in order to allow other functions to associate and register with these hooks.

As a WordPress developer, you can use this function to create your own new custom action hook by specifying the name of this hook as the function argument, and you can optionally pass any additional parameters to it in case you want to use your own callback functions as follows:

do_action( ‘action_name’, [argument1], [argument2] );
  • Function do_action_ref_array :

This function is similar to do_action() in its operation, but its arguments are passed through an array. They are useful when your brokers are already in a matrix. Or when you need to pass a lot of arguments to a function.

$arguments_array = array( ‘arg_1’, ‘foo’, true, ‘arg_4’ );
do_action_ref_array( ‘example_action’, $arguments_array );
  • Function has_action :

This action function checks whether a particular hook has been linked to a function. It receives two arguments, the first is the name of the action hook, action_name, and the second is an optional argument that represents the name of the callback function to be checked, function_to_check.

If you pass both parameters to this function, it will return false if the callback function specified with the specified action hook is not registered.
If you pass only the first argument, it returns true if any callback function is linked to the first argument, which represents the hook name, and false otherwise.

has_action( ‘action_name’, ‘function_to_check’ );
  • Did_action function :

This function is used to find out the number of times any action hook occurred during the operation of a site. It returns to you an integer that represents the number of times the hook occurred in your site.

For example, if there is a hook that occurs or occurs several times on the site and you want to run the callback function only the first time this hook is run and not the following times, you can write the following code:

add_action(‘example_action’, ‘example_callback_function’
function example_callback_function() {
if( did_action( ‘example_action’ ) === 1 ) {
// Here write the code you want to execute when the ‘example_action’ hook occurs for the first time only
}
}
  • Function remove_action

This hook function removes or unlinks the callback function associated with the specified action hook. For example, you can use this function to remove the default WordPress functions associated with built-in actions hooks and replace them with your own.

remove_action( ‘action_name’, ‘function_to_be_removed’, [priority] );

In order to use this function, both the function_to_be_removed arguments representing the callback function you want to unbind and the priority argument must be the same as the arguments of the function through which add_action() is binding.

It should be noted that you cannot call this function directly within the code, but rather you must need to call it from within another function, and you also cannot remove the callback function through this function before you link it to the original or after it is run in the code.

For example, you can add WooCommerceUsing this function to remove the default thumbnail of the product from the store’s home page through the following code:

remove_action( ‘woocommerce_before_shop_loop_item_title’, ‘woocommerce_template_loop_product_thumbnail’, 10 );
  • Function remove_all_action

This function is used to remove all callback functions associated with a particular action hook. All we have to do to do this is pass it an argument that represents the name of the required hook. You can also optionally pass a priority parameter as follows.

remove_all_actions( ‘action_name’, [priority] );

Be careful that this function cannot be called from within the same code as the action hook that you want to unlink from the callback function, otherwise you will end up with code that contains an infinite loop.

  • Function doing_action

This function returns a boolean value (true or false) that specifies whether the action hook passed as its argument is currently running. All you have to do is pass it an argument that represents the name of the hook, as follows:

if ( doing_action( ‘action_name’ ) ) {
// execute your code here
}

This function can also be used without arguments, in which case it will return true if any hook occurs during the site’s operation, as follows.  

if ( doing_action() ) {
// the code here is run when any action is fired
}

Filter Hooks in WordPress

Filter Hooks are defined in WordPress through the apply_filters function , which has the following form:

apply_filters( ‘filter_name’, ‘value_to_be_filtered’, [optional_arguments] );

whereas:

filter_name is a string representing the name of the filter.

 value_to_be_filtered is a variable representing the value that should be modified or filtered and returned

 [Optional_arguments]  are arguments that can optionally be passed to the filter.

Core WordPress uses a lot of built-in filters to modify the data used by its various functions. For example the following filter hook:

apply_filters( ‘admin_footer_text’ , string $text )

It is a filter through which the text string (Thank you for using WordPress) that is usually displayed in the footer of the site admin control panel can be modified, as shown in the following image:

admin_footer_text

The most important functions of filter hooks in WordPress

In this paragraph, we explain the most important programming functions that are used with filter hooks in WordPress

  • function add_filter

The add_filter() function is considered one of the most widely used and famous filter hook functions. It is used to connect a callback function to a specific filter hook. Therefore, we pass two arguments to this function, which are the name of the filter and the callback function to be associated with this filter, as follows:

add_filter( ‘hook_filter_name’, ;‘callbak_function’)

Similar to the add_action() function, this function can also optionally take two additional arguments:

Priority  is an integer representing the execution priority for each associated callback function to run in its own priority order

The number of arguments Accepted args is an integer that you can pass to the function if you need to pass an additional number of arguments to the callback function associated with the filter (the callback function accepts one argument by default).

We mention here that the callback function that connects with the filter hooks must return the value after executing its code as follows:

add_filter( ‘hook_filter_name’, ‘example_callback’ );
function example_callback( $example ) {
// Maybe modify $example in some way.
return $example;
}
  • function has_filter

This function verifies that the specified filter is associated with any callback function. It receives two arguments, the first is the name of the filter and the second is an optional argument that returns the name of the callback function as follows:

has_filter( ‘filter_name’, ‘function_to_check’ );

If you pass only the first argument to the has_filter function, it will return True if filter_name is associated with any function whatsoever.
If you pass two arguments to it, it will return an integer representing the priority value assigned to this function over this filter in case the mentioned callback function is associated with the specified filter, and it will return the logical value False otherwise.

  • Function application_filters

The function of this function is similar to the do_action() function in action hooks, as it runs any callback functions associated with this filter wherever this function exists within the WordPress code.

You can also use this function to create a new custom filter by specifying the filter name and filter value as arguments as follows

apply_filters( ‘filter_name’, ‘value_to_filter’, [argument1], [argument2] );
  • Function application_filters_ref_array

This function is similar to the application_filters function that we explained in the previous paragraph, but the difference here is that all the arguments passed to this function are grouped in the form of an array.
Therefore, this function is useful if there are multiple arguments that need to be passed or if the arguments already exist within an array.

// an example array
$arguments_array = array( ‘some_value’, ‘foo’, false, ‘another_value’ );
apply_filters_ref_array( ‘example_filter’, $arguments_array );
  • function current_filter

Although this function’s name is related to filters, it returns the name of the current hook being run in WordPress, whether its type is a filter hook or an action hook. It does not need to pass any arguments to it because it works within the callback function code and is used as follows

function example_callback() {
echo current_filter(); // ‘the_title’ will be echoed
return
}
add_filter( ‘the_title’, ‘example_callback’ );
  • Function remove_filter

This function deletes the callback function bound to the filter hook specified as an argument and works similarly to the remove_action function for action hooks.

This function can be used to delete registered default WordPress functions associated or registered with a specific filter hook, and link your own callback functions when needed.

remove_filter( ‘filter_name’, ‘function_to_be_removed’, [priority] );

To unbind a callback function bound to a particular filter, both the function_to_be_removed and priority arguments must be identical to the arguments used when binding the callback function to that filter.

If the filter was added from within a class, which usually happens when adding it through a custom WordPress plugin, then you need to access the class variable to be able to remove the filter as follows.

// access the class variable first, and then remove the filter through it
global $some_class;
remove_filter( ‘the_content’, array($some_class, ‘class_filter_callback’) );

For example, the WooCommerce plugin uses a callback function called wc_lostpassword_url() associated with the lostpassword_url filter hook in order to redirect users who click the Forgot your password link?

When any user clicks on this link they will be taken to a dedicated page with a custom URL as follows

 www.domain/my-account/lost-password

Instead of taking them to the regular URL used to log in to WordPress

www.domain/wp-login.php

Let’s say you want to reset this function and send users to the default password recovery page or send them to any other custom page you want, you can unbind the wc_lostpassword_url callback from the filter like this:

remove_filter( ‘lostpassword_url’, ‘wc_lostpassword_url’, 10 );
  • Function remove_all_filter

This filter function removes all callback functions that are hooked into a specified filter hook, similar to the remove_all_actions function for action filters.

remove_all_filters( ‘filter_name’, [priority] );

For example, Advanced Excerpt removes all default functions associated with the _excerpt filter and get_the_excerpt filter. It then binds its own callback functions to these filters.

if ( ! has_filter( ‘get_the_excerpt’, array( $advanced_excerpt, ‘filter_excerpt’ ) ) ) {
remove_all_filters( ‘get_the_excerpt’ );
remove_all_filters( ‘the_excerpt’ );
add_filter( ‘get_the_excerpt’, array( $advanced_excerpt, ‘filter_excerpt’ ) );
}
  • Function do_filter

This filter function checks whether the specified filter is currently running, returning True if the hook is running and False otherwise.

if ( doing_filter( ‘save_post’ ) ) {
// run your code here
}

A practical application for dealing with hooks in WordPress programmatically

After you have formed a comprehensive theoretical idea about the mechanism of hooks in WordPress, their types, and their most important programming functions, let us now apply all of this through an integrated practical example that shows you the use of hooks.
Before that, I remind you that working programmatically with hooks within WordPress requires that you have basic knowledge of developing custom WordPress plugins , developing WordPress templates from scratch, and how to create a child template from an existing template .

Hook methods in WordPress plugins are usually registered in dedicated PHP files within plugins, or within WordPress themes (in the functions file of the main theme, functions.php , or within a child template of the main template activated on your site).

Knowing that you can also edit the WordPress kernel files directly to record the hooks, but this method is not preferable because you will lose any modifications you make if you update WordPress. For the same reason, it is not preferable to add your hooks inside the main template, but rather within a child template of the template itself.

For example, to illustrate how hooks work in WordPress, we will create a new plugin called tryhooks that will customize the logo and link displayed on the WordPress login page located at http://example.com/wp-login.php using hooks.

Instead of displaying the WordPress logo in the interface shown above, clicking on which leads to the official WordPress website, we will display the logo of our WordPress site in Arabic, and clicking on it will take us to the main page of the site as follows:

To do this we will create the beginning of a folder for the custom plugin named tryhooks in the /wp-content/plugins/ directory. Inside this folder, we create a file called tryhooks.php, edit it and add the following code to it:

<?php
/*
Plugin Name: Tryhooks
Version : 1.0
Description: This is a Test plugin to Demonstrate hooks in WordPress.
Author : Ola Saleh
Author URI : https://www.wpar.net/author/engolasaleh/
Text Domain: tryhooks
*/
//====1 change WordPress logo image =====
add_action( ‘login_enqueue_scripts’, ‘my_login_logo’ );
function my_login_logo() { ?>
<style type=“text/css”>
#login h1 a, .login h1 a {
background-image: url(<?php echo content_url(); ?>/plugins/tryhooks/images/wparlogo.png);
height:300px;
width:300px;
padding-bottom: 5px;
background-size: 300px 300px;
background-repeat: no-repeat;
}
</style>
<?php }
//====2 change login logo URL=====
add_filter( ‘login_headerurl’, ‘my_login_logo_url’ );
function my_login_logo_url() {
return home_url();
}
//====3 change login logo URL title=====
add_filter( ‘login_headertext’, ‘my_login_logo_url_title’ );
function my_login_logo_url_title() {
return ‘The Arabic Guide to Learning WordPress’ ;
}

Once you save this file and go to the site’s control panel and choose the Add-ons tab, you will find the name of this add-on appearing in the add-ons list. Activate it on your site.

Now go to the site’s login page and notice how the page has been modified according to how the add-on works. Let’s explain what we did in the previous code.

Explanation of the add-on code:

The most important part of using hooks correctly is to know what actions and filters are associated with each page of your WordPress site. In the previous code, we took advantage of the following hooks in WordPress to accomplish the required:

  • login_enqueue_scripts action hook : which is used to add formats or scripts to the WordPress login page. We have linked it to the callback function code named my_login_logo , which will change the image of the default WordPress logo displayed on the login page and the logo of our website, which we saved in the images folder within the plugin folder.
  • login_headerurl filter hook : which is used to change or modify the URL of the logo displayed on the login page of a WordPress site by linking it to the my_login_logo_url callback function that will return a link to the home page of our site.
  • Login_headertext filter hook : which is used to customize the link text of the site’s login page with our site name wpar by linking it to the my_login_logo_url_title callback function.

To use these hooks to accomplish what is required, we have, as shown in the code, registered or linked each of these hooks to a hook function appropriate to its type (we connect the action hook to the add_action function and the filter hook to the add_filter filter function), then we pass a callback function to it as a reference to be executed. At every hook drop.  

The next step is to define each callback function and write the custom code that we want to execute inside it. Remember, these functions will be executed automatically when each of the hooks that we have associated with it occurs.

  • Function my_login_logo(): In this function, we have written a code that replaces the WordPress logo using the CSS property of the background image with the logo image of our WordPress site in Arabic, which we have saved in a folder called images within the tryhooks plugin folder, which is located in the content folder. For this we used the content_url() function to retrieve the path to the content folder and then added the rest of the logo image path.
  • Function my_login_logo_url() : In this function, we wrote code that returns the URL link to the home page of the current site displayed in the browser by calling the ready-made function home_url()
  • Function my_login_logo_url_title(): By default, the logo link contains the following text ‘Powered by WordPress’, so in this function we have written a programming code whose task is to change the text of this link and return the following text to the filter ‘The Arab Guide to Learning WordPress’ in order to explain to the visitor the purpose of the link before clicking on it.

Now the WordPress system will run these methods and execute all the code we wrote every time a hook occurs while our site is running.

Thus, we have finished customizing the WordPress login page by changing the WordPress login logo, the logo URL, and the logo text using hooks within our own plugin, without the need to change the code in WordPress itself.

Important resources for learning WordPress hooks professionally

You may feel overwhelmed by the large number of hooks provided by WordPress and the dependencies associated with them, and think that dealing with them is difficult to learn!
Don’t worry, this is normal at first, and with time you will get used to it and be able to find the appropriate hook for your needs easily and link your code to it flexibly.

WordPress provides you with thousands of existing hooks in order to facilitate your work, and all you have to do is identify them, link your code to them, and use them optimally to customize your site.
Here are some helpful resources to help you learn more about hooks in WordPress and determine the perfect hook for your needs.

Reference 1 : This link explains hooks within the guide explaining plugins in WordPress. Through it, you can find basic information about hooks, and see detailed documentation about all actions and filters in WordPress and how they work.

Reference 2: This link includes an easy-to-use search tool through which you can search for anything in WordPress and find all the hooks, functions, classes, etc. This link also shows you, under the section (NEW & UPDATED IN WORDPRESS 5.9), all the new and updated components in The latest current version of WordPress.

Reference 3: This link displays a table that includes an ordered list that includes the names of all WordPress hooks, what type of each hook is (filter hook or action hook), when did each hook first appear, and is it still supported in WordPress or has it been excluded.

Reference 4: This reference includes a link to the official WordPress Developer Guide, which contains a link that shows you all the action hooks in WordPress, and another link that shows you all the filter hooks in WordPress.

Conclusion

With this, we have reached the end of our article in which we tried to explain to you in a simplified manner the concept of hooks in WordPress, and introduce you to how to use them and take advantage of them to run custom code at certain points during the implementation of the WordPress core or the implementation of one of the plugins or templates on the site.

At the end of the article, we have provided you with a group of useful resources that will help you learn more about the hooks that WordPress supports. It includes hooks every time it does something. There is a procedure for almost everything you do within the site, so we recommend that you read these resources and benefit from them in learning how to deal professionally with These hooks are a must-have for any WordPress developer.

Finally, if you use your own hooks to develop your own themes or plugins. We recommend that you give these hooks unique and simple names that express them, and that you ensure that you document these hooks and explain their working mechanism accurately and in detail in order to help other developers interact with your code and benefit from it optimally.

Avatar photo
I am a young man who has been working in WordPress and e-marketing for 10 years. I would like to share my experience with you so that we can become professional in WordPress I will be happy to share the experience with you.