Clean Up Your functions.php file by Using Classes in WordPress

If you have done WordPress development for any extended perious of time, you inevitably go searching for different ways to do things. A lot of times what these tutorials will do will give you some code and say…

Just add the following snippet of code to your functions.php file and all will work great.

Having written tutorials for WordPress, I have been guilty of this. It’s a quick and easy way to give a user some functionality.

That’s all well and good when your first starting out, but after awhile if you’re not careful, you can end up just adding and adding and adding to your functions.php file and then pretty soon you have a massive document on your hands before you know it. It’s never good from programming perspective of maintainability and scalability to have large amounts of code concentrated that perform many diverse aspects of functionality located in a single place.

But what’s the alternative? I’m glad you asked. Well, by using classes in WordPress you can divide the code that handles the functionality for your website up into smaller parts each representing one piece of functionality. And in your functions.php file all you have to do is include the class. Then your functions file becomes a lot more lightweight and it is much nicer to work with when you have to use it for something else.

Let’s see an example of this. Let’s do something fairly standard that you’d normally do in WordPress: registering a shortcode. For the sake of example, let’s register a shortcode that does something simple like say hello. Maybe a previous tutorial would tell you to do something like put the following in your functions.php file…

function sayHelloShortcode($atts, $content = null) 
{
    return 'I am happy to say hello!';
}
add_shortcode('say_hello', 'sayHelloShortcode');

So now if you’d typed [say_hello] in into the editor in a page or post the text “I am happy to say hello!” would appear. Real world shortcodes are obviously much more complex than this but for the sake of example is best to keep things simple.

Now that’s nice. But as you add more and more shortcodes (and more complex shortcodes with large amounts of code inside the body of each function, your functions.php file could start to get out of hand.

So how can we solve this problem? Well it would actually make sense to take all of our shortcodes out of functions.php and group all of our shortcodes inside of one class. That way, we can have them all centralized in one location and if we want to add more, we’ll know where do do it. So if we wanted to add a shortcode to a class, this is how we’d do it. Create a new PHP file called Shortcodes.php and add the following…

<?php
class Shortcodes {
    function __construct() {
        add_shortcode('say_hello',  array($this, 'sayHelloShortcode'));
    }

    function sayHelloShortcode($atts, $content = null) 
    {
        return 'I am happy to say hello!';
    }

}
?>

So the add_shortcode action will be executed inside the constructor of the class when the class is instantiated.

There is one distinctive difference when adding in action hooks or filters inside a class in WordPress. When specifying the callback function you have to specify that you want to access the callback function inside of **this** class. To do this you use the following syntax.

add_shortcode('say_hello',  array($this, 'sayHelloShortcode'));

Whereas before you just used the string name of the callback…

add_shortcode('say_hello', 'sayHelloShortcode');

That’s really the only difference. After this you can create as much as you want and add as many functions as you want just as you were doing to your functions.php file and you can have the same functionality. Only now this piece of functionality is nicely wrapped up in your class. For example, if we wanted to extend the shortcodes class by adding more shortcodes, we can just add another “add_shortcode” to our constructor and add the callback function.

<?php
class Shortcodes {
    function __construct() {
        add_shortcode('say_hello',  array($this, 'sayHelloShortcode'));
        add_shortcode('say_something_else',  array($this, 'saySomethingElseShortcode'));
    }

    function sayHelloShortcode($atts, $content = null) 
    {
        return 'I am happy to say hello!';
    }

    function saySomethingElseShortcode($atts, $content = null) 
    {
        return 'Something else';
    }
}
?>

The other great part of this is that if you use classes to do other things like register custom post types, or add meta boxes, you can give your functions really simple names like “register” or “add” and there’s no risk having a conflicting function name from some other plugin or anywhere else because your function is wrapped up this class. You could use “register” as a function name in each one of your classes. That’s great! If you tried to do this functions.php you’d get a duplicate function definition.

But there’s one important final step we have to do and that’s actually create an instance of this class so that the code will actually run because the PHP classes don’t run by themselves they have to be declared and called. But this is easy enough. You can just create a variable and give it any name and set it equal to a new instance of the class right after the closing } of your class.

...

    function saySomethingElseShortcode($atts, $content = null) 
    {
        return 'Something else';
    }
}

$shortcodes = new Shortcodes();

Then in your functions.php file just include this class and all the code inside of it will run.

include('Shortcodes.php')

You could even throw all of your classes in a “classes” folder and include it…

include('classes/Shortcodes.php')

That way you can keep your project directory nice and organized.

As far as naming your classes go, you’re usually okay but sometimes it’s a good idea to add a prefix to your class name. It’s conceivable that perhaps one of the plugins you have activated has also used a class named “Shortcodes.” So it’s a good idea to add a short sequence of characters to the beginning of your class name (e.g. MYNAME_Shortcodes). I use NBS (for nine bit studios). So my classes have names like NBS_Shortcodes, NBS_Meta, NBS_Portfolio. You just want to make sure that you don’t use the WordPress prefix WP_. WordPress uses this prefix so use your own to make it distinct from core WordPress classes.

So what are you waiting for? Get into your functions.php file and start grouping some of those functions into classes! You’ll be happy you did 😉

, 9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

9 Responses to Clean Up Your functions.php file by Using Classes in WordPress

  1. Billy says:

    Exactly the info I was looking for. Thanks! Just out of curiosity, what makes the classes run automatically? Shouldn’t we have to manually instantiate them using new MyClass();? Anyway, looking forward to trying this. Thanks!

  2. Billy says:

    Ah, nevermind! I see that you covered this. I skipped over that part because I was so stoked to find such an awesome article. 😀

  3. Billy says:

    Quick question, but how would you recommend handling utility functions? For example, I have a function that returns a date/time ISO866 format with proper timezone … What would be the best way to call this from the template if it were ported to a class? Instead of putting $foo = new MyClass(); in the class file, would I just instanciate the class on the templates when I need them? Does that make sense? Thank you!!!!

    • 9bit Studios says:

      I do something along the lines of creating a classes.php file where I have all of my include(‘MyClass.php’) statements. Then I’ll create instances below the include statements.

      $myClass = new MyClass();

      To use these classes in another template file (e.g. sidebar.php) you have to declare the variable as global (kind of like you have to do with $post sometimes). So at the top of sidebar.php you have to declare

      global $myClass;

      Then you can call your public methods in your template file…

      $myClass->my_method();

      And then of course don’t forget to include(“classes.php”); in functions.php

      • Billy says:

        AWESOME! Thank you!!!! 🙂

        Great info. You just helped me super-charge my functions/templates.

        Much appreciated.

        Have a nice day!

  4. Eduardo says:

    Thanks for posting about this. I think I figured out something that can be a problem, tough.
    Often, in functions.php we need to check if a method already exists, using the method function_exists(), before calling the action, filter or shortcode callback .
    Placing that inside a class, I’m not realizing a way to do that from inside it. Any thought on that? Thanks in advance!

    • Ian says:

      Hey there Eduardo. If I understand what you are bringing up, would it only be a matter of utilizing method_exists instead? Obviously if your class is non-static you’d have to create an object instance first (or have access to it somehow), but if it were static you wouldn’t have to worry about it.

  5. steedz says:

    Thx a lot! Exactly the information i was looking for!

Leave a Reply

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