Using Filter Hooks in WordPress Child Themes

In this post you’ll learn to take advantage of Filter Hooks in your WordPress Child Themes. Filter Hooks are an essential weapon in your WordPress Theming arsenal. With them you’ll have almost complete control over the HTML created by your WordPress Theme—without touching any template files.

Warning: things will get a little technical on this one but hang in there—you’re about to become an expert in this stuff.

How WordPress Filter Hooks Work

Filtering a function is actually pretty easy—once you know how WordPress filters work. But if you’re going to filter something in your Child Theme functions you’re going to have to get your hands messy with a little PHP. Luckily, it’s pretty easy stuff.

If you’re just getting started messing around with PHP I want you to remember this one crucial tip: the functions file must begin and end with the opening and closing PHP tags. With no extra lines before or after. Something like this:

<?php
// We're going to be pasting our code between those PHP tags above and below this comment
?>

The Anatomy of a WordPress Filter Hook

Let’s look at the anatomy of a WordPress Filter Hook.

// We'll use this form if we're going to just outright replace something
function my_function_name() {
  // Your custom code goes here, between the curly braces
}
add_filter('filter_name','my_function_name');

Take a look at the above example. We just wrote some PHP code. We wrote a function:

function my_function_name() {
    // Your custom code goes here, between the curly braces
}

And then we told WordPress to take that function and use my_function_name instead of the original content, or code, that was returned by filter_name.

add_filter('filter_name','my_function_name');

filter_name is the key here. Somewhere in the bowels of WordPress, or our Parent Theme code, there is a function that looks something like this:

function super_stuff() {
    $stuff = 'bacon';
    echo apply_filters ( 'filter_name' , $stuff );
}

Did you catch that last line in the super_stuff function? echo essentially means “put it on the screen” but the really important bit here is apply_filters. That’s where we’re getting our filter_name, the filter we’re, um, well, filtering. Any function using apply_filters, whether it’s in the WordPress code or your Parent Theme code, will let itself be filtered by another function in a plugin or, more importantly to us here, a WordPress Child Theme.

This is huge. But if you don’t get it yet, that’s OK. I’m a big believer in teaching through copy and paste. So let’s get to it and start filtering some Theme functions.

Filtering Theme Functions

Activate the Child Theme, Chiron, we made in Modular CSS in WordPress Child Themes and make a functions file if you haven’t already (chiron/functions.php). We’re going to start out by filtering with one of the more complicated looking Theme functions in our Parent Theme, Thematic, thematic_postheader.

Actually it’s not that complicated at all. Let’s have a look at an abridged version of thematic_postheader that contains almost everything you’ll need to know.

// Information in Post Header
// Basically the stuff you see at the top of every post
function thematic_postheader() {
    global $id, $post, $authordata;

    // The Post Title 		    
    $posttitle = apply_filters('thematic_postheader_posttitle',$posttitle); 

    // The Post Meta    
    $postmeta = apply_filters('thematic_postheader_postmeta',$postmeta); 
    
    // Is this a post or a page?
    if ($post->post_type == 'page' || is_404()) {
        // If it's a page show only the Post Title
        $postheader = $posttitle;        
    } else {
        // If it's a post show the Post Title and The Post Meta
        $postheader = $posttitle . $postmeta;    
    }
    
    // Echo the Post Header
    echo apply_filters( 'thematic_postheader', $postheader ); // Filter to override default post header
}

Did you look at the code? There’s 3 apply_filters in there, 1 for thematic_postheader itself and 2 for the content inside of it, the Post Title and the Post Meta.

Alright. Let’s do something stupid and replace everything in our Post Headers with … bacon. Copy this code snippet to your Child Theme functions file, save and reload your test site.

function childtheme_postheader() {
	echo 'bacon';
}
add_filter('thematic_postheader','childtheme_postheader');

Your Post Titles and Post Meta should have all disappeared and been replaced with … bacon. Not especially useful but you just learned how to filter the output of any filterable function.

Let’s try another—more useful—function. Delete the previous snippet from your functions file.

At some point you might want to add a containing div to all the Post Titles in your theme. Perhaps you want to add a complicated background effect or need to float something in a particular way. We’re going to filter the variable in thematic_postheader that’s returning the Post Title and make that change to the code output by the Theme template files—without actually editing any template files.

Copy this code snippet to your Child Theme functions file, save and reload your test site.

function childtheme_posttitle($posttitle) {
	return '<div class="containing">' . $posttitle . '</div>';
}
add_filter('thematic_postheader_posttitle','childtheme_posttitle');

Check out your test site source code. You just added a containing div to every Post Title on your site. With only 4 lines of code.

Take note of what we did differently in this function. We added a variable in line 1 and returned it in line 2. Doing this lets you use the content of the original function you’re filtering. This is powerful stuff.

You’ve now been armed with enough information to go out and start filtering Parent Theme functions in your WordPress Child Themes (and you’re halfway to becoming a WordPress Plugin author too). Now all you need are some functions to filter.

Where To Look For Filters

Besides digging through the code (which I always find useful) there are two good resources for finding where all the filters you need are hiding.

How To Modify WordPress Themes The Smart Way

This post is part of the series How To Modify WordPress Themes The Smart Way.

  1. WordPress Child Theme Basics
  2. Modular CSS in WordPress Child Themes
  3. Using Filter Hooks in WordPress Child Themes
  4. Using Action Hooks in WordPress Child Themes

36 thoughts on “Using Filter Hooks in WordPress Child Themes

  1. Except in very rare and unusual situations, you should always return and not echo when using filters. While the above code technically works in that particular situation, it’s very, very poor practice for many reasons, including:

    * echo‘ing doesn’t allow other functions to filter what you have changed it to. If a filter is registered after yours, it can’t do it’s job. And if you don’t want other functions touching your result, then hook in later than the default 10. This is why it’s called a filter and not an action (actions are standard hooks, filters are for filtering data).

    * What if the result of the filter is grabbed at one point in the page and outputted elsewhere? Echo would screw that up. It’s a lot more common than you think, especially when dealing with standard WordPress filters.

  2. ilia says:

    chris, i’d like to thank you for doing all this. for dealing publicly with advanced wp stuff, with functions and filters and such. you are taking wp-related blogging to a different level, i kid you not. there’re very few resources on the web where one could get more than stuff on customizing links color or using a new plugin. all these recent efforts that aim at bringing wp closer to being a good cms are really, really welcome, and you’re a valuable source for this.

    again, thanks alot.

  3. Pingback: Usiamo i filtri nei child theme per WordPress | Altamente Decorativo

  4. Ian,
    I am really enjoying the series.
    I don’t really get the comment from ‘Viper007Bond’. Have you already fixed this? If not, which bits of code need to change. If so, please note that in your reply.

    • Nothing needs to change for the tutorial. Just something that needs to change in the Thematic code base which, again, won’t really affect this tutorial. Sort of the grammatical equivalent of me forgetting to put a spacebetween two words. It’ll be fixed in the next release of Thematic.

      • No, my comment was entirely about the code in this article. I have never read the source of Thematic, so if it doesn’t do something like this:

        <?php echo apply_filters( ... ); ?>

        and is instead missing the “echo”, then yes, I guess the echo is needed inside of the filter.

        However this is the “proper” way to do it from a coding viewpoint: http://themeshaper.pastebin.com/f20c26599

  5. Pingback: WordPress Weekend Resources - May 8, 2009 | Theme Lab

  6. Pingback: WordPress Weekend Resources - May 8, 2009 | cyooh.com

  7. I definitely learned a lot in this tutorial. Thank you for taking the time to explain filters and hooks. Your simple exercises made it easy for me to understand how they work in theme development. Thanks.

  8. I found you tutorial fairly dull…until you replaced the header with bacon, at which point you turned the corner from pedestrian to pure genius.

    It was as if the scales had fallen from my eyes and I saw the entire world wide web in a new light. Scalability, usability, inheritance, and bacon all one in the same and delicious!

    You sir are a visionary. My compliments to the chef.

  9. Pingback: Structure du framework Thematic | Eiffair

    • This is very useful. Thank you for explaining PHP in a way I can understand it. My latest project was completed successfully thanks to you.

      Thematic child themes are a fantastic way of developing WordPress sites and I’m not going back to doing them the old way.

      This particular tutorial just helped me get through a client’s request.

  10. Robert Neuschul says:

    A small comment on the code you’ve used above for checking for is_home() and is_frontpage() etc.

    A discussion at http://cmslamp.com/category/wordpress/ [foot of that page] explains how standard checking may not be sufficient to cover all combinations of circumstances. The author puts forward a more exhaustive function for front page checking. Having tested this myself I can agree with him: he’s correct and his new function is more accurate. I’d argue that that code or a variant of it should be included in the Thematic code base. This function is especially useful where one is using WP as a static CMS for documentation on a single host with many different httpd aliases or rewrites all pointing at a single “site”.

    Finally, thanks for a truly superb series of articles about WP coding and the Thematic stuff in general. Your writing is exceptionally clear and concise, which makes a wonderful change from all the dross one so often finds.

    Robert

  11. Pingback: Get Ahead(er) – Open Source Design - fall09

  12. Pingback: Once and for all – the difference between Filters and Hooks – Open Source Design - fall09

  13. Hi there,

    I’d like to use a filter hook with a conditional phrase (like the following) in order to link to different style sheets on different pages. The stylesheet “frontpage.css” has been customized already.

    function kickass_create_stylesheet($content) {
    $content .= “t”;
    $content .= ”
    “;
    $content .= “nn”;
    return $content;
    }
    if (is_front_page()) {
    add_filter(‘thematic_create_stylesheet’, ‘kickass_create_stylesheet’);
    }

    But this doesn’t really work out, as you may have guessed. How can I call a different style sheet for each page?

  14. Pingback: 10 Tutorials to Take Your WordPress Development Skills to the Next Level | Web Design Byte

  15. Pingback: Wordpress Hooks: Actions and Filters « My Graphic Friend's blog

  16. Pingback: Get Ahead(er) – Open Source Design - Spring10

  17. Pingback: Let’s be clear on this – the difference between Filters and Hooks – Open Source Design - Spring10

  18. Thanks Ian. You are making this accessible even to those of us who majored in English. WordPress was starting to look to me like a tiger with bloody slashing claws and Thematic makes it more like a friendly cat, if still a bit mysterious and aloof. Really appreciate the good documentation.
    jlp

  19. Pingback: Tutorial: Manage Custom Fields With Custom Write Panels – Open Source Design - Spring10

  20. Pingback: How to Create your own BuddyPress theme (Part-1)

  21. Pingback: How to Create your own BuddyPress theme (Part-1) | CG Stream

  22. martha says:

    Well, I’m reading this series with considerable hopefulness and playing along at home… but I’ve gotten error messages with the bacon-replacement technique, too! Could it be WP’s friendly little editor in admin? (Yes, I have made sure there are no spaces or lines before the opening or after the closing php.)

  23. karl says:

    I have to agree with Martha. I tried this several times over and all I got was errors as well.

    Fatal error: Cannot redeclare _verify_isactivate_widgets() (previously declared in /home/website/public_html/blog/wp-content/themes/chiron/functions.php:9) in /home/website/public_html/blog/wp-content/themes/thematic/functions.php on line 116

  24. You don’t actually need to close the php tags, I’d actually recommend not closing the php tags in the functions.php as you can have EOF or EOL hidden characters that actually produce “output” such that calls to header() or session_start() etc will fail as you’ve included a file that starts the output buffer.

  25. I’ve been copying the functions snippets above and it seems that your Thematic theme may have been updated to not include the referenced functions any longer for my function snippet does not perform as described. In fact, what I get is an echoed version of the function at the top of my page, and not actually processed as php script.

Comments are closed.