In WordPress, a hook is a way for one piece of code to interact with, or “hook into,” another piece of code. There are two types of hooks in WordPress: actions and filters.
An action hook allows you to insert custom code at various points (actions) in the WordPress core code. For example, you might want to add a line of code that executes when WordPress displays a blog post, or when a user logs in.
A filter hook allows you to modify, or “filter,” various types of data in WordPress. For example, you might want to modify the content of a blog post before it is displayed, or modify the HTML of a widget before it is rendered.
You can use hooks to customize and extend WordPress without modifying the core code. This is a best practice because it allows you to upgrade WordPress without losing your customizations.
Here is an example of an action hook in WordPress:
function my_custom_code() {
// do something
}
add_action( 'publish_post', 'my_custom_code' );
In this example, the my_custom_code function will be executed whenever a post is published. The publish_post action hook is triggered by the WordPress core code when a post is published.
Here is an example of a filter hook in WordPress:
function modify_post_title( $title ) {
return 'Modified: ' . $title;
}
add_filter( 'the_title', 'modify_post_title' );
In this example, the modify_post_title function modifies the post title by adding the text “Modified: ” to the beginning of the title. The the_title filter hook is triggered by the WordPress core code whenever the post title is displayed. The modified title is then returned by the function and displayed in place of the original title.