As significant as the WordPress API is in building plugins, themes, and applications, there are often times where we may find ourselves needing to write custom functions to achieve something that we know WordPress already does.
Case in point: With Page Template Dashboard, I wanted to be able to show the name of the template rather than the filename. I knew WordPress was doing it, but I couldn’t find an actual API function for it.
So what’s the best thing to do in this particular situation?
Don’t Reinvent The Wheel
I hate using that cliche, but it works, right? In cases like this, we know WordPress is capable of doing something (because it’s doing it natively); therefore, we shouldn’t have to write a function to duplicate its functionality.
I think all developers – at some point throughout their career – assume that it’s just easier to write it themselves. Personally, I think this is wrapped up in wanting to see if they can as well as showing off that they can.
But here’s the thing: We know it can be done because it has been done, and because it has been done, there’s no need to prove that you can do it.
This is not to say that developers shouldn’t try to figure out how to solve problems that they find interesting, or try to duplicate functionality that they find in their favorite applications – I actually thing this is a great way to learn, but there is a time and a place for it.
In our case, we’re afforded the luxury of having the source code for the entire WordPress application on the web and on our hard drives. When we know that WordPress is doing something that we want to do, we can issue a simple
grep (depending on how in love you are to the Terminal, I guess 🙂 when finding functions in WordPress that we know already exist.
But here’s the thing: When you set it out to see how WordPress – or any application for that matter – is doing something, don’t start with looking for function names. Instead, look for some unique string that you know on which a function operates.
For example, I knew that WordPress was specifically looking for
Template Name. As such, I could do a find to see where this was located in core. Once done, I was able to use that function.
But Heads Up!
There is a danger in doing this: functions can become deprecated, have their names changed, and/or completely be removed from the core application, so if you opt to go this route then it’s critically important that you make sure your work is stable with the latest release.
Anyway, next time you find yourself trying to do something that WordPress – or any other application – is already doing, first look to see if you can leverage the existing function before writing your own.