If you are developing plugins or themes for WordPress, the chances are big you are using Classes to format your code, especially if you have more experience with development and object-oriented programming (OOP). And did you know that in WordPress, autoloading classes with PHP is possible? With autoloading, classes are automatically loaded when they are called. Pretty useful, if you ask me.

But wait, what is object-oriented programming?

But wait, you are going way to fast! I just started developing. So what on earth is object-oriented programming?

In essence, object-oriented programming revolves around the use of so-called objects. Objects can have certain data attached to them. In PHP, this is in the form of properties. Additionally, objects can have certain functions, called methods. Often, these methods are used to manipulate properties.

In programming, an object is often represented by a class. Let’s give an example in PHP.

<?php
        class Someclass {
            private $property;

            public function __construct() {
                 $this->property = 1;       
            }

            public function getProperty() {
                  return $this->property;
            }

        }

        $class = new Someclass();   // Constructs the class
        echo $class->getProperty(); // Echoes 1

So in the above example, we have a class called Someclass with a property called $property and the method getProperty. Properties within a class are accessed by using $this->property.

By initiating the $class using new Someclass, we are constructing a new object from this class. We then can access this object methods and properties as long as they are public.

Now if you really like this, there is a Canadian fellow named Carl Alexander who is writing a lot about object-oriented programming. You may want to read this introduction to object-oriented programming for WordPress.

Getting back to autoloading

But that’s enough of the introduction! Let’s get back to the actual topic of autoloading.

Now PHP comes with a very useful function called autoloading. What it basically means is that every time when you call a class, it is automatically loaded. This is particulary useful if you have to include many libraries or scripts.

Calling classes in WordPress without autoloading

Without autoloading, you have to require or include every class manually as shown the example below. Obviously, if you are using a lot of classes, you require a lot of include statements.

<?php   
	include_once('/folder/class.php');
	$class = new Folder\Class();
?>

Calling classes in WordPress with autoloading

With autoloading, you can just call the class and it will load. Providing you have set it up correctly, of course. The following code would automatically include the given class and execute it if you would have been using autoloading.

<?php
	$class = new Folder\Someclass();

For the above example to work correctly, the class should be properly namespaced and placed in the right directory. Namespacing is a PHP utility that indicates to what namespace a given class (and file) belongs. A namespace often matches the build-up of a directory.

So, in the above example, the new Folder\Class would be placed in folder/someclass.php. The given class would then start with indicating the namespace using PHP namespaces. In this case, Folder.

<?php
	namespace Folder;

        class Someclass {
            public function __construct() {}
        }

So what about classes that are placed in directories with multiple folders? It’s quite easy: just namespace according to the folder structure. For example, use namespace Folder\Subfolder.

Different standards of autoloading

If you have been looking into autoloading, you may have seen terms such as PSR-0 and PSR-4 before. Now, these terms indicate the standard for how to deal with file paths and namespacing. In other words, how should namespaces and folders be structured accordingly?

The current standard is PSR-4, so luckily we only have to dive into this standard. So what does PSR-4 entail? Let’s look at our previous example:

  • If we call the class, we use the namespace and class: new Folder/Someclass()
  • This logic resembles the folder structure, namely folder/someclass.php
  • In someclass.php, we use namespace Folder in our first rule of coding to indicate to what namespace it belongs.
NamespaceClass NamePath
FolderFolder\Someclassfolder/someclass.php

In a very basic form, PSR-4 is about this: the namespace of a class follows the path (in other words, the folders or directories) in which a given class is placed. There are some additional rules which you may inspect here.

How to set-up WordPress autoloading

So how can you enable WordPress class autoloading? PHP comes with a handy function called spl_autoload_register which is used to register new functions for autoloading classes. Let’s look at a basic example. We assume this file is placed in the functions.php file of our WordPress theme.

<?php
    spl_autoload_register( function($classname) {

    $class      = str_replace( '\\', DIRECTORY_SEPARATOR, strtolower($classname) ); 
    $classpath  = dirname(__FILE__) .  DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . $class . '.php';
    
    if ( file_exists( $classpath) ) {
        include_once $classpath;
    }
   
} );

So what does the above example do?

  1. Whenever a class with $classname is called (for example, Folder/Someclass), it will lowercase this class and separate any backward slash for the slash that is used to separate directories.
  2. Subsequently, it adds the classes folder and any higher directories in front of this class resulting in $classpath. In this example, $classpath can be something like wp-content/themes/theme/classes/folder/someclass.php

If we would have added our previous class Someclass within classes/folder/someclass.php in your theme, we can now call new Folder\Someclass(); without manually including it!

From our WordPress scripts collection, there is also a free WordPress class autoloader available.

WordPress Autoload Classes and WordPress Naming Conventions

Now as you may have noticed, we so far ignored the WordPress naming conventions for classes. For PHP classes, WordPress dictates to use the class prefix before the filename. So in our example, we end up with folder/class-someclass.php.

So how can we adjust our existing autoloader to comply with the standards of WordPress? We have to split up our namespaced folder structure and add the class- prefix to the actual file. It’s quite easy using PHP’s explode function:

<?php   
    $parts      = explode('\\', $classname);
    $class      = 'class-' . strtolower( array_pop($parts) );
    $folders    = strtolower( implode(DIRECTORY_SEPARATOR, $parts) );
    $classpath     = dirname(__FILE__) .  DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . $folders . DIRECTORY_SEPARATOR . $class . '.php';

Autoloading and composer

The real power of using autoloading is making use of modules from Composer.

For example, we have written various scripts for WordPress such as the WP Custom Fields script and the WP Components script. Using Composer, these can easily be included within a theme or plugin.

In the following example, we assume a new theme is developed. Within the root folder of the theme, we place a file called composer.json. It may look like this:

{
    "name": "makeitworkpress/autoloading-demo",
    "description": "Demo for autoloading with WordPress",
    "repositories": [        
        {
            "type": "vcs",
            "url": "https://github.com/makeitworkpress/wp-components.git"
        }       
    ],
    "require": {
        "php": ">=7.0",
        "makeitworkpress/wp-components": "dev-master"
    },
    "homepage": "https://github.com/makeitworkpress/wordpress-autoload-class/"         
}

This file indicates it is going to use a custom repository from GitHub. Obviously, you need to use Composer’s update command from our terminal.

  • Go to your terminal, and make sure you are in the right location (for example, the folder of the theme you’re developing).
  • Type composer update –prefer dist. Composer will now load the required modules in a folder named vendor. Because you are using composer update –prefer-dist, it will only load the distribution version of the repository and not all .git related code.
  • Composer will also automatically set-up some scripts for autoloading..

Our module has been imported! The next you want to do is to require and execute the autoloading script that has been included by Composer. So just add the following line to your functions.php:

/**
 * Uses composer to autoload our vendor modules. 
 * Make sure you are using composer update --prefer dist in your terminal first, so these modules are loaded!
 */
require_once 'vendor/autoload.php';

/**
 * This loads the WP Components module, as it is included in the example...
 */
$components = new MakeitWorkPress\WP_Components\Boot();

It’s that easy. The vendor modules now only need to be called and are automatically loaded.

Done! Questions?

Alas! You have harnessed the power of class autoloading in WordPress. Feel free to leave any comments or questions below. There is also a complete overview of the code from this article available on GitHub.