What are Hooks in WordPress

Hooks are functions that can be applied to an Action or a Filter in WordPress themes and development. WordPress Actions and Filters are features that theme and plugin authors can update to alter the basic WordPress functionality.

hooks in wordpress

Modification functions WordPress Actions/Filters can be linked to (hooks) WordPress. It’s crucial to note, however, that actions and filters are not interchangeable. When a specific event occurs in WordPress, actions are executed. Filters allow you to change the way certain functions work. Both filters and actions utilize the same arguments to hook them. They are, nevertheless, functionally and behaviorally distinct.

In WordPress, here’s an example of a hook that’s been utilized with a filter:

1
2
3
4
5
6
7
function wpb_custom_excerpt( $output ) {
  if ( has_excerpt() && ! is_attachment() ) {
    $output .= wpb_continue_reading_link();
  }
  return $output;
}
add_filter( 'get_the_excerpt', 'wpb_custom_excerpt' );

The preceding code produces the wpb custom excerpt function, which is hooked into the get the excerpt filter.

The following is an example of a hook used in conjunction with an action:

1
2
3
4
function mytheme_enqueue_script() {
    wp_enqueue_script( 'my-custom-js', 'custom.js', false );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_script' );

The code in the example above creates a function called mytheme enqueue script, which is connected to the wp enqueue script’s action.

How to Unhook from Actions and Filters

To remove a hook is quite simple. Use the function remove_action or remove_filter along with the name of the hook, function, and priority. The priority is optional and helpful if you have to unhook a function that is hooked more than once and you only want to remove a specific occurrence of that function.

remove_action( $tag, $function_to_remove, $priority );
remove_filter( $tag, $function_to_remove, $priority );

Now that we have looked at the basics of how functions are hooked and unhooked, let’s take a look at a few real world examples of some different hooks in action.

More: