What is hooks in WordPress and how to use them

Posted By Satyam Sharma | 21-Sep-2018


In this blog, I am giving the brief introduction about WordPress hooks and also show how the WordPress hooks made work easy for WordPress developer. 

So let’s start with the definition of hooks in WordPress. Hooks are basically the functions which can be put to an Action or a Filter in WordPress. WordPress has included “hooks” so that people can “hang” their own code on those hooks. For better understand the WordPress hooks lets put an example of real hooks uses in our houses which we basically use for hanging our clothes and some other things on the wall or gate.

Like this WordPress also uses their hooks to hang the other external function in the WordPress theme to make some extra functionality.

Mainly WordPress provides us two types of hooks 

1. Action Hooks
2. Filter Hooks

The major difference between these hooks is that Action hook is used to add some functionality and the filter hook is used to manipulate some existing functionality in WordPress. Even I will give the brief description with the example of both these hooks.


Action Hooks:

When we talking about the action hook we mainly use action hook to add some new functionality to our theme. Let see the below example of a simple action Hook.

function custom_enqueue_script() {
    wp_enqueue_script( 'my-custom-js', 'custom.js', false );
add_action( 'wp_enqueue_scripts', 'custom_enqueue_script' );

In the above example, we add a new js file in our existing theme by giving a function name custom_enqueue_script and applied that function to our action hook. 

In action hook, we give two parameters. The first parameter is where we have applied our action function and the second parameter is our function name which we made by himself.


Filter Hook:

When we talk about the filter hooks, Filter hook is basically used for manipulating some existing functionality in WordPress. To better understand let see the below example.

function custom_excerpt( $output ) {
  if ( has_excerpt() && ! is_attachment() ) {
    $output .= 'custom_content';
  return $output;
add_filter( 'get_the_excerpt', 'custom_excerpt' );

In the above example, we manipulate WordPress existing excerpt function. Or we can say that we add some extra content in the excerpt function. Whenever we excerpt the content we can find that our written content in the custom function will show after the end of the excerpt content.

We use these function in our WordPress theme function file i.e functions.php file.

As seen the above blog, we can say that hooks make the work so easy for WordPress developer.





Request for Proposal

Recaptcha is required.

Sending message..