Common Filter Hooks in WordPress: Usage and Examples
In WordPress, common filter hooks like
the_content, the_title, and wp_title let you modify content, titles, and page metadata before they display. You use add_filter('hook_name', 'your_function') to attach your custom function to these hooks and change output dynamically.Syntax
The basic syntax to use a filter hook in WordPress is:
add_filter('hook_name', 'your_function', priority, accepted_args);
Where:
- hook_name is the name of the filter hook you want to use.
- your_function is the name of your custom function that modifies the data.
- priority (optional) controls the order your function runs (default is 10).
- accepted_args (optional) is how many arguments your function accepts (default is 1).
php
add_filter('the_content', 'modify_content', 10, 1); function modify_content($content) { // Modify and return content return $content . '<p>Appended text.</p>'; }
Example
This example shows how to add a message at the end of every post content using the the_content filter hook.
php
<?php add_filter('the_content', 'add_custom_message'); function add_custom_message($content) { if (is_single()) { $content .= '<p><strong>Thank you for reading!</strong></p>'; } return $content; } ?>
Output
When viewing a single post, the post content will show normally with "Thank you for reading!" appended at the end.
Common Pitfalls
Common mistakes when using filter hooks include:
- Not returning the modified value from your function, which breaks the output.
- Using the wrong hook name or misspelling it.
- Not checking context (like
is_single()) and modifying output everywhere unintentionally. - Forgetting to set the correct number of accepted arguments if your function needs more than one.
php
<?php // Wrong: Does not return modified content add_filter('the_content', 'wrong_modify'); function wrong_modify($content) { $content .= '<p>Oops!</p>'; // Missing return statement } // Right: Returns modified content add_filter('the_content', 'right_modify'); function right_modify($content) { $content .= '<p>Fixed!</p>'; return $content; } ?>
Quick Reference
Here are some common WordPress filter hooks and what they modify:
| Filter Hook | What It Modifies |
|---|---|
| the_content | Post or page content before display |
| the_title | Post or page title before display |
| wp_title | Page title tag content |
| excerpt_more | Text shown at the end of excerpts |
| widget_title | Title of widgets |
| comment_text | Text of comments |
| body_class | CSS classes for the body tag |
| post_class | CSS classes for post containers |
Key Takeaways
Use
add_filter with the correct hook name to modify WordPress output.Always return the modified value from your filter function to avoid breaking output.
Common hooks include
the_content, the_title, and wp_title.Check context inside your function to apply changes only where needed.
Set the correct number of accepted arguments if your function requires more than one.