How to Use Hooks in WordPress Plugin: Simple Guide
In WordPress plugins, use
add_action to run your code at specific points and add_filter to modify data. Hooks let your plugin interact with WordPress without changing core files.Syntax
WordPress hooks come in two types: actions and filters. Use add_action('hook_name', 'your_function') to run code at a point, and add_filter('hook_name', 'your_function') to change data passed through WordPress.
Each part means:
hook_name: The name of the hook where your code runs.your_function: The name of your function to execute.
php
<?php // Add an action hook add_action('init', 'my_plugin_init_function'); // Add a filter hook add_filter('the_content', 'my_plugin_modify_content'); function my_plugin_init_function() { // Code to run on WordPress initialization } function my_plugin_modify_content($content) { // Modify post content return $content . '<p>Appended by plugin.</p>'; } ?>
Example
This example shows a plugin adding a message at the end of every post content using a filter hook.
php
<?php /* Plugin Name: Simple Content Append Description: Adds a message at the end of post content using a filter hook. Version: 1.0 Author: Your Name */ add_filter('the_content', 'append_custom_message'); function append_custom_message($content) { if (is_single()) { // Only on single posts $content .= '<p><strong>Thank you for reading!</strong></p>'; } return $content; } ?>
Output
On single post pages, the post content will show normally plus: "Thank you for reading!" in bold at the end.
Common Pitfalls
Common mistakes when using hooks in plugins include:
- Not using the correct hook name, so your function never runs.
- Forgetting to return the modified data in filter functions.
- Running heavy code inside hooks that slows down the site.
- Not checking conditions (like
is_single()) causing unwanted changes everywhere.
php
<?php // Wrong: filter function does not return modified content add_filter('the_content', 'bad_filter'); function bad_filter($content) { $content .= '<p>Oops!</p>'; // Missing return statement return $content; } // Right: always return modified content add_filter('the_content', 'good_filter'); function good_filter($content) { $content .= '<p>Fixed!</p>'; return $content; } ?>
Quick Reference
Remember these tips when using hooks in your WordPress plugin:
- Use
add_actionto run code at specific events. - Use
add_filterto modify data passed through WordPress. - Always return data in filter functions.
- Use conditional checks to limit where your hook runs.
- Keep hook functions efficient to avoid slowing the site.
Key Takeaways
Use add_action to execute code at WordPress events and add_filter to modify data.
Always return the modified data in filter hook functions to avoid breaking output.
Check conditions inside your hook functions to control where they apply.
Use correct hook names exactly as WordPress defines them.
Keep hook functions fast and simple to maintain site performance.