One of the most regularly used developer features in WordPress is its Hook system.
Hooks are what make WordPress so extendable and allow you to build anything on the foundation
of WordPress, from a blog to an online e-commerce platform. Let's dive into what Hooks are,
how they work and how you can use them in your WordPress themes and plugins.
Hooks allow your theme or plugin code to interact with or modify the execution of a WordPress
request at specific predefined spots. There are two types of Hooks, Action Hooks and Filter Hooks.
These are more commonly known as actions and filters. To understand how Hooks work,
let's look at how a Hook is defined in WordPress Core. In the WordPress front-end request lesson,
you learned about the wpsettings.php file and how this file sets up the WordPress environment.
If you scroll down to about line 643 of this file, you will see the following line of code,
DoActionInnit. Here the DoAction function defines an action Hook with the Hook name of Innit.
You can read more about this Hook in the Innit Hook documentation.
As a developer, you can Hook into this action and run your own code when this Innit action is fired.
Essentially like being able to add your own code inside the wpsettings.php file at this point,
but without actually modifying the core file. You can use Hooks in your WordPress themes and
plugins to add your own functionality to WordPress or to modify the default functionality.
To see this in action, let's create a simple example of how you could use a filter Hook
to modify the content of a post. To do this, you're going to create a small plugin.
Don't worry if you've never worked with plugins before, but do check out the introduction to
plugins module to learn more about them. For now in your code editor, browse to your wpcontent
plugins directory and create a new file called wplearnhooks.php.
Then add the following code to this file.
Now browse to the WordPress admin of your local WordPress installation,
go to plugins and activate your new plugin. So we click plugins and activate wplearnhooks.
Then browse to the front end of your site and view any post or page.
In this example, I'm going to view the sample page.
You will see that the content of the page now has the text "Thanks for reading"
added to the end of it. If you deactivate the plugin, the text will disappear.
This is a very simple example of how you can use a filter hook to modify the content of a post.
Don't worry if none of this makes sense right now, as we will cover this in more detail
in the following lessons on action hooks and filter hooks.
Thanks!