Using the WordPress apply_filters Function for Dynamic Content

Tuesday, January 26th 8:52pm Matt

In a WordPress plugin you can filter many values including the title and content of a post using:

add_filter('the_content', 'MyPluginClass::FilterTheContent');

This is pretty handy, but sometimes when you’re writing a WordPress theme you want to allow plugins to add content, not just filter the usual content. Using apply_filters makes this pretty easy because you can call apply filters with custom “tags” and it will just work. For instance in your theme you can put:

<?php

    $theMessage = apply_filters('CustomThemeMessage', '' /* default value: empty string */);

    if (!empty($theMessage))
    {
        echo '<div class="Message">', $theMessage, '</div>';
    }

?>

If nobody ever filters on the tag ‘CustomThemeMessage’ it’s fine, your theme won’t break or anything. But plugins that know this tag is available can use it:

add_filter('CustomThemeMessage', 'MyPluginClass::FilterTheContent');

When you’re developing themes and plugins in tandem, this is incredibly useful and robust. It’s also not as risky as filtering a tag like ‘the_content’ where a mistake can really mess up your site. It will also be more performant when you only need the custom content on one or a few of the pages on your site.

Submit a Comment