Changing How Your WordPress Post Titles Appear, A First Filter Hook Tutorial

This week, we explain how to write your first filter hook in WordPress. If you like it, video’s right here:

If you prefer words, here’s what we did. We’re trying to change all post titles on the site to include a word or symbol. It’s little bit of a contrived and silly example, but we’re mostly trying to make the simplest filter example we can. So if you know all about hooks and specifically filters, you just need this little code snippet, which can be found in our big article on action and filter hooks:

add_filter('the_title', 'wpshout_filter_example');
function wpshout_filter_example($title) {
	return 'Hooked: '.$title;
}

The Steps to Change Your Titles

If you need a bit more explanation, here’s what this does step-by-step:

  1. We use the add_filter function provided to WordPress that when it “applies” the 'the_title' filter we want our function to be called. That’s the second thing we’re giving it: the name of our function.
  2. Then our function is taking the value passed to it by the 'the_title' filter, that’s the whole next line.
  3. Finally, we added the word “Hooked: ” to the front of the passed value $title and pass it back with the return keyword.

The code we don’t need to write is what WordPress does with this. WordPress handles that. Basically our code has taken something that WordPress will otherwise use unmodified, and modified it. WordPress uses our modified version in the place of the title, and we don’t have to write any more than these four lines. It’s a really powerful system!

There’s a great deal more to know and understand hooks and filters in WordPress well, and our article on them is a great overview of the core distinctions and important details. Happy hacking!


Add a Comment

Your email address will not be published. Required fields are marked *