Writing A WordPress Filter To Modify Post/Page Titles

I was recently working on a new WordPress theme when I had need to modify the title of pages before output. The style I was attempting to use involved wrapping <span> tags around the title (inside of the href tags). The wp_list_pages() function returns pages (which are basically the same as posts) and has several arguments that you can pass to customize it’s output. However, modifying the title output is not one of the arguments.

Filters to the rescue! I simply opened up the functions.php file and added a function like this:

Pretty simple, eh? All that is left to do is to register this function as an appropriate filter, which you can do like this:

The first parameter tell WordPress which function/activity you want to “hook” into. The second parameter is the name of your function. The final parameter is a priority specifier. The lower this priority number the earlier it will execute.

Done! Now instead of output like this:

I get this:

For extra credit you actually throw all of this into a plugin. That way you wouldn’t necessarily have to modify any of your theme files.