Using PHP Classes and Functions in WordPress

Creating custom functions in your WordPress template’s function.php file is a regular thing for many of us. What you might not know is how easy it is to wrap them in a class, or even why you would. Wrapping them in a class keeps them both organized and self-contained from other functions that may have the same name. This can be especially important if you are using third party plugins.

Lets get started by creating a new class and function

class my_new_class {
function do_something() {
echo 'Add a custom function';
}
}

Here we have created a new class and function that will simply echo “Add a custom function”.

Call your new custom function in your desired WordPress template file

<?php my_new_class::do_something(); ?>

That’s it. Super simple and clean. So if you’re wanting to write better PHP functions for WordPress, or are just having some general bugs in WordPress code or Admin, this may help. I had one function on a site that would cause jQuery to act up in the Admin. Wrapping it in a class fixed it.

Published by

Tim Bunch

Tim Bunch is a Web Designer and Social Media Specialist at CapEd FCU from Boise, Idaho. As a web standards fanatic, he passionately pursues best practices in web design. He also actively engages people on a wide range of topics in a variety of social media networks. Tim is also an avid Wordpress developer, music maker, coffee drinker, and child raiser. @timbunch

Leave a Reply

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