How do WordPress hooks (actions and filters) work? Can you give examples?
How do WordPress hooks (actions and filters) work? Can you give examples?
WordPress hooks serve as points in the system which let you add your own code to transform behavior without modifying core files.
There are two types:
- Actions – “Do something”
- Filters – “Change something”
1. Actions
During WordPress execution, there are specific times at which you can add custom functionalities through actions.
- Syntax:
add_action(‘hook_name’, ‘your_function_name’);
Example: Add custom text after each post
function add_custom_text_after_post($content) {
if (is_single()) {
$content .= ‘<p>Thanks for reading!</p>’;
}
return $content;
}
add_filter(‘the_content’, ‘add_custom_text_after_post’);
2. Filters
Filters enable data modification during both data usage and display operations including modifications to post content and excerpts along with titles.
- Syntax:
add_filter(‘hook_name’, ‘your_function_name’);
Example: Change the excerpt length
function custom_excerpt_length($length) {
return 20;
}
add_filter(‘excerpt_length’, ‘custom_excerpt_length’);