Autoloading classes in WordPress Plugin

Say no to require_once while developing WordPress plugin!!!!

Most of the wordpress plugin developers uses classes as containers to develop the plugin which means that they wrap their functions inside the class to make the plugin development more structural. This is the best practice for plugin development but as per OOPs concept, you have to make an object of class to call the function if the class is non-static and to make the object, you have to require the class using wither require_once or include_once method. This is an old fashion for requiring the classes whenever we make an object of class in wordpress plugin development.

What to do instead?

Simple answer is “use the spl_autoload_register() function”

How to use the spl_autoload_register() ?

In this tutorial, you will learn how to use the spl_autoload_register()  function provided by wordPress for autoloading classes in WordPress Plugin. 

Lets start with the very basic structure I always follow while start the development of my wordpress plugin. My plugin directory structure looks something like this

Explanation

I will not explain the entire directory structure because most of us knows it very well that how this structure will work but I  would like to explain the one folder “includes” because this is the most important folder for this tutorial

All my class files reside under this “includes” folder. I always use the wordpress naming conventions to create the class name. As per wordPress naming convention, Class file names should be based on the class name with class- prepended and the underscores in the class name replaced with hyphens, for example WP_Error becomes: class-wp-error.php (source)

Now we know that our class name will be always separated by underscore and class file name will always start with class- so we can easily get the class file name if we know the name of class with the following code

Now lets have a look at wordpress function spl_autoload_register()

This simple function provided by wordpress is used to autoload the function defined under the callback.

Most of the wordpress plugin developer avoid the use of this function but trust me this function is our friend. After reading this tutorial, you will also say the same so lets continue.

Use the given below code inside the main file of your plugin just under the top comments for essential plugin code

Note: I have added if condition and used “Wpfkr”. Wpfkr is the prefix given to this class name so that this function will autoload only the classes with my prefix and will not affect the other plugins or themes.

This is all about Autoloading classes in WordPress Plugin. Feel free to ask questions in our Questionsbank forum