What actually are Hooks in WordPress?

0 Shares

So, you have heard a lot about Hook, haven’t you? There are hundreds of articles out there about hooks. What are hooks, how do they work, bla bla bla..

What actually are Hooks in WordPress?

Do you REALLY understand what actually are hooks? If your answer is ‘Yes’, well, you can ignore this post.
But, if your answer is ‘No’, then let me tell you about Hooks in a way that perhaps nobody uses.

Hooks are “places” to alter or add something in your WordPress!

Places?! Nobody defines Hooks as places, right?

Well. You have noticed that I said “alter or add something”. Meaning, Hooks are used to alter/modify something that is already there or to add something new. These 2 are the main goals of using Hooks. So, hooks are of 2 types-

  • Action Hook – To add something new
  • Filter Hook – To alter or modify something

Action Hook

As I mentioned before, Hooks are “places”. So, Action Hooks are places that allows you to add something at the location that it was declared! Let me give you an example.

Say, we are creating a theme. At the footer area of the theme, we have a navigation menu added.
Now, you are thinking, what if someone wants to add a copyright text just below the menu?

This is where Action Hook comes into the picture. We can allow anybody to add their own text (or an image, or anything else) by defining an Action Hook here.

So, we’ll write our code like this-

If you see carefully, just after where the code for navigation menu ends, we have defined a “place”. Anybody now can add his own text, image or anything else at this place from an external file. Which could be a plugin, or a child theme.

Wondering how to add custom text at that place?
Just write a function and “hook” that function at the predefined place.

You can even send an email, perform a database query etc, whatever you need, at that “place”!

Filter Hook

Unlike Action Hooks, Filter Hooks allow you to alter/modify an existing data. For example, in the theme we were talking about, we want to show today’s date in the header area. So, we have written our code like this-

It will print Today’s date is 2018-03-07.

Now, what if we want to allow others to modify this date, as we have kept it hardcoded?
Yes, you got it right. We’ll make our code hook-able!

It will still print the same, Today’s date is 2018-03-07.

This date is now hook-able from external sources. If another developer wants to alter this and show current dynamic date, he needs to write code like this-

Need help with your WordPress tasks?

0 Shares