Get started building your Woocommerce store or web application -- Call us today at 7868174424

Hooks in WordPress

Hooks in WordPress are a very useful tools, WP is known to base its operation on events and procedures. During the system run cycle there are different parts that run at different times. In the ecosystem of this framework, hooks are one of the most powerful tools. It is notable that thanks to them the operation of the site can be modified at different points, through code. In this way, understanding how they work is one of the most important goals to be achieved as a developer. Hooks form the basis of plugin and theme activity because they facilitate adding their functionalities to the system. At the same time, they are the channels of interaction of the custom code with the WordPress core. Even the same core uses them extensively. In this article hooks will be characterized, their structure and way of operation will be explained, their classification will be described and examples of how to use them will be shown.

How are hooks classified?

In general there are 2 types of hooks: action hooks and filter hooks. To use either one, the same structure is declared. When using any type of hook, you need a function in which the desired code will be executed, and then a call to a method that registers this function, called callback, on behalf of a specific hook. Action hooks interrupt the natural flow of the WordPress code to run the code added by the developer. After this, they return to the natural execution of the system without modifying anything. In short: they interrupt the flow of site code, execute custom code, and follow the normal flow of system execution. Action hooks do not return a value. For their part, filter hooks change the information they receive, in a specific way. That modified information will then be used by another part of the code. Filter hooks are always expected to return some element.

Estructura de los action hooks y grupos en los que se dividen

The structure of an action hook is as follows:

// Action Hook Structure
add_action(string $action, callable $function_identifier, int $priority, int $quantity_parameters);

in which the following parameters exist:

  • $action: required parameter of type text string. It is the identifier of the action (hook, hook) to which the function that is passed by $ identifier_my_function will hook.
  • $function_identifier: required parameter of text string type. It is the identifier of the function that is created to execute custom code, the operation to be performed.
  • $priority: optional parameter of type integer. Declare the order in which each method related to this hook will be executed. If this parameter is omitted, it has a default value of 10. The lower the number, the higher your priority. If there is an equal value for more than one function hooked to the same hook, the conflict is resolved by ordering the functions according to the moment in which the procedure of hooking the function to the hook was performed.
  • $quantity_parameters: optional parameter of type integer. Defines the number of parameters that are passed to the function. If not declared, by default the value 1 is taken.

There are many action hooks. The official WordPress documentation catalogs them in 10 groups, according to different criteria:

Action hooks categories Descriptionn
Action hooks that are executed during a typical request They are executed when a logged in user opens the main page of the site
Action hooks that are executed during the request for an administrative page Called when a logged in user opens the posts page
Action hooks related to pages, posts, attachments or categories from the administration Executed when adding, removing, editing, or updating operations are performed on a page, post, attachment, or category. Also included are action hooks that are executed when doing these operations with taxonomies
Action hooks related to trackback, pings and comments They are executed when certain operations are performed on these elements of the WordPress logic
Action hooks from blogroll Run when blogroll links are added, removed, or edited
Action hooks related to the feed They run at the time the site feed operations are performed
Action hooks related to the topic Are called when operations related to the site theme are completed
Action hooks related to administrative activities They are executed at the time of performing an operation that can only be completed from administrative profiles
Action hooks advanced They run when WordPress is determining which posts to show, when the loop runs, when plugins are activated, and others of that nature
Action hooks related to administrative logging They are executed when the login page performs operations for management, authentication, password reset and others of the user management type.

Structure of the filter hooks and groups into which they are divided

Filter hooks have the following structure:

// Estructura filter hook
add_filter(string $filtro, callable $identificador_mi_funcion, int $prioridad, $cantidad_parametros);

 

only the first parameter differs from action hooks:

  • $filter: required parameter of type text string. It is the identifier of the filter hook to which the function that is passed by $identifier_my_function will hook.

There are also many filter hooks. The official WordPress documentation determines 19 groups, according to different criteria:

Categories of filter hooks Description
Filter hooks related to database operations on posts, pages and attachments They are executed when reading and writing operations are performed in the database on this type of WordPress elements
Filter hooks related to database operations on pings, comments and trackbacks They run when executing read and write operations in the database on this type of elements
Filter hooks related to link database operations Refers to filters related to links to pages, posts, files, feeds and others. Does not refer to blogroll links
Filter hooks related to dates and times Process information about date and time generated by WordPress functions
Filter hooks related to authors and users They process information that is read and written to the database that deals with authors and users of the system
Filter hooks related to blogroll Contains filters related to blogroll links
Filter hooks related to blog information and options Groups filters that process information obtained and saved in the database about the blog and its options
Filter hooks related to general text Contains filters that process text in a general way
Filter administrative hooks Filters in this category relate to WordPress administrative pages
Filter hooks for the rich text editor These filters modify the settings of the rich text editor
Filter hooks related to the topic This category contains filters that process links, themes, templates, and theme style files
Filter hooks related to user registration and login Contains filters to process authentication, user registration errors and emails, validation of user names, and attempted authentication of an already authenticated user
Filter hooks related to redirect and rewrite These filters have to do with WordPress handling of rewriting rules
WP_Query filter hooks These filters are executed by the WP_Query object while building and executing queries to the database
Filter hooks related to media files Groups filters that are used to integrate images, photos and audios
Advanced filter hooks Includes advanced filters related to internationalization, miscellaneous queries and other fundamental WordPress functions
Filter hooks related to widgets Contains filters added by widgets present in the WordPress core
Filter hooks related to the administrative bar These filters are related to the administrative bar added in WordPress version 3.1.0

How to use an action hook

An example of how to use an action hook in WordPress would be the following:

// Archivo: /wp-content/themes/mi-tema/functions.php

/**
 * Action hook
 */
function my_action_hook_code(){
    echo '<h1>Custom code inserted from a hook</h1><br>';
}

// Hook
add_action('init', 'my_action_hook_code');

In this case, the hooking of the ‘my_action_hook_code’ function is performed on the ‘init’ action, without determining priority, which defaults to 10 when executing the function. The ‘init‘ action is typically used by plugins to initialize. It belongs to the group of actions that are executed during home page requests.

How to use a filter hook

An example of how to use a filter hook in WordPress would be the following code snippet:

// Archivo: /wp-content/themes/mi-tema/functions.php

/**
 * Filter hook
 */
function my_filter_hook_code($excerpt_text){
    $excerpt_text = '<i>Código personalizado anclado al filter hook \'the_excerpt\'</i><br><br>';
    return $excerpt_text;
}

// Hook
add_filter('the_excerpt', 'my_filter_hook_code');

In the example, the function ‘my_code_filter_hook‘ is hooked to the filter hook ‘the excerpt’, without determining priority, which predefined it the value 10, and without declaring number of arguments, ensuring the value for this parameter of 1. The filter hook ‘the_excerpt‘ belongs to the category of those related to reading from the publications, pages and attachments database. Applies to the summary of the posts or the content of the posts if no excerpt has been defined, which is obtained from the database, before printing on the page  

Conclusions

Hooks in WordPress are a powerful tool and constitute one of the main goals to master in the development world with this framework. To use them, you must have the code that will process the information or the code fragment that you want to execute, encapsulated in a function. The hook to which the function will be anchored must also be defined. Optionally, the number of parameters that must be passed and the priority that the method execution must have are defined. These elements are divided into 2 groups: the action hooks and the filter hooks. Action hooks do not return information and are used to execute snippets of custom code as if they were inside the WordPress core stream. Filter hooks take information before printing it on th page or saving it in the database, allow it to be processed and then return it to the code flow, so that it can be worked on if desired. Both action hooks and filter hooks are categorized into a different groups according to different criteria. Hooks are one of the most important concepts in WordPress, if you are still interested in the development of themes or plugins, I suggest the following links

How to create a plugin in WordPress?

Taxonomies in WordPress. What are they for? How are they created?

Custom Post Type in WordPress (CPT)  

WordPress official doc (Hooks)