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’m not going to explain the entire directory structure as most people are familiar with how that structure works, but I will explain one “includes” folder as it is the most important folder for this tutorial.

All class files are in this “includes” folder. Always use WordPress naming conventions when creating class names. As per WordPress naming conventions, class filenames should be the class name prefixed with the class name and underscores in the class name should be replaced with dashes.

Confused??

Have a look at the example below.

For example WP_Error should be  class-wp-error.php (source)

Now I know that class names are always separated by underscores and class file names always start with class. So you can easily get the file name of the class if you know the name of the 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

Loading