If you’re not clear about the difference between WordPress actions and filters, you may end up breaking the page layout of WordPress – maybe days, months, or even years after you’ve written and implemented a new filter hook. The difference can be difficult for new developers to grasp – after all, hooking an action or filter runs your code, either way, right? Well, yes, it does, but filters can be executed several times, in different locations as the webpage is being built (header, body, footer, etc.), and even in the admin back-end. But more importantly, filters do not send anything to the webpage! Filter hooks receive their data / text as an argument, and then “return” the modified (or original) data / text at the end. They do not use “echo”, “print”, “printf”, etc. – they should not send anything to the webpage. If you need to output something directly to the webpage, use an action – that’s what they’re for. ;-)
A good filter hook:
function my_filter_hook( $text ) {
$text .= 'Adding some text.';
return $text;
}
A bad filter hook:
function my_filter_hook( $text ) {
echo 'Adding some text.';
return $text;
}
How common is this problem?
Unfortunately, it’s much more common that you might think. The “the_content” filter, for example, is often a source of problems – developers may think their content filter hook is executed only once, when WordPress includes the post content, but post content may be required in header meta tags, widgets, in the footer, or even filtered in the admin back-end. The “the_content” filter may even be used on completely unrelated text, to expand shortcodes or format text. If you’re sending anything to the webpage from a filter hook, you’re doing it wrong – use an action instead. ;-)
How do you know if you have a badly coded filter?
If you activate a plugin that uses the “the_content” filter (as one example), and the webpage layout is affected, you may have an incorrectly coded filter hook. This problem is so common that plugin authors often avoid using the “the_content” filter for that very reason.
This problem can be frustrating for end-users to diagnose as well – often the only way is to start disabling plugins / change themes until the problem goes away, and reporting the problem to the plugin / theme author can also be challenging since it may, or may not, be caused by a filter hook – and if it is, determining which filter is affected can require some coding effort / knowledge. This problem is so common, and so challenging for users to diagnose, that I even wrote a plugin specifically to fix and report which content filter hooks incorrectly send output to the webpage.