Get it All

For nearly as long as there has been a WordPress, themes have included a functions.php file. This file provides a lot of extra, for lack of a better word, “functionality” to your WordPress blog. And while so much else about WordPress has changed over the years, it is quite remarkable how little about the functions.php file has evolved.

This is particularly true in light of WordPress’ ability to create child themes. Child themes are separate themes which extend the functionality of their “parent” themes by overriding key theme files. A child theme may only have a style.css file, to refer back to the parent. Or it might include a single.php file, because in the case of this one theme, you want all the functionality of the parent, but you’d like single posts and pages handled differently.

The trouble is: while a template file can override it’s parent, the WP functions.php file just basically loads the namespace with a bunch of free-floating functions, usually prepended with the name of the theme. There isn’t any “overriding” a function in PHP; the only thing you can do is write another function with still another name or prefix. That’s not very efficient use of the namespace and a recipe for confusion.

Instead, what I decided to try was putting my entire list of functions inside a class. Call it ParentFunctions. Inside this class, I also included a self-named initialization function that would do the adding of filters and actions as necessary. Then, all I need to do is instatiate my object – and be sure to call the “global” in each file where its necessary – and I’ve got an extensible model from which to create child themes.

Let’s look at ParentFunctions:

Among the advantages, here, is that our namespace is much cleaner. So is our code: instead of having to trawl through a couple dozen prefix_function_name entries, I can get straight to function_name. But better still, if I want to modify how a function works in a child theme, that’s even easier:

Using classes in your WP functions.php file provides a cleaner, easier interface for extending your themes for whatever you need.