What is hooks?
In WordPress, a hook is a mechanism that allows users to modify or add functionality to a WordPress theme or plugin without directly editing its core files. Hooks provide a way to interact with the code at specific predefined points called “hooks”.
There are two types of hooks in WordPress:
- Action Hooks
- Filter Hooks
1. Action Hooks:
- Action hooks allow you to insert custom code at specific points in the WordPress execution process.
- Actions are triggered by events such as when a post is published, a theme is activated, or when the admin bar is initialized.
- Developers can use action hooks to add, modify, or remove functionality at these specific points.
Example of an action hook in WordPress:
add_action('publish_post', 'my_custom_function');
function my_custom_function() {
// Your custom code here
}
Code Explanation:
add_action(‘publish_post’, ‘my_custom_function’);: This line adds an action hook. It tells WordPress to execute the function my_custom_function when the event ‘publish_post’ occurs. The event, in this case, is when a post is published.
function my_custom_function() { // Your custom code here }: This is the custom function that will be executed when the ‘publish_post’ event happens. You would replace the comment with your own custom PHP code, allowing you to perform specific actions when a post is published.
2. Filters Hooks:
- Filter hooks allow you to modify data as it is being processed or displayed.
- Filters take a piece of data, process it, and then return the modified data.
- They are commonly used to modify the output of functions, customize text, or alter various aspects of content.
Example of a filter hook in WordPress:
add_filter('the_title', 'my_custom_title');
function my_custom_title($title) {
// Your custom code to modify the title
return $title;
}
Code Explanation:
add_filter(‘the_title’, ‘my_custom_title’);: This line adds a filter hook. It instructs WordPress to apply the function my_custom_title to the output of the the_title function. Filters allow you to modify data before it’s displayed or used elsewhere.
function my_custom_title($title) { // Your custom code to modify the title return $title; }: This is the custom function that acts as a filter. It takes the original title as a parameter ($title), allows you to modify it with your custom code, and then returns the modified title. Your custom logic goes inside the function to alter the title as needed.