Member-only story
Using namespaces and autoloading with Composer in WordPress plugins
Namespace and autoload are not widely adopted when it comes to WordPress plugin development, since WordPress’s commitment to backward compatibility with PHP as old as 5.2.4, whereas, namespace is only available since version 5.3.0. In addition, Composer requires PHP 5.3.2+. However, if you are creating a WordPress website which will be run on a server whose PHP version is newer than 5.3.2, you are safe to use namespace and autoload with Compser.
In this tutorial, I will create a WordPress plugin which generates a shortcode which displays today’s date. First, I will use require_once to include classes and then I will use namespace and autoload with Composer to include classes. Without further ado, let’s get started now.
Creating the Plugin Directory
We need a bootstrap file and some folders to contain the PHP classes we will create inside the folder of our plugin. Let’s go ahead and create them now:
Then, let’s open the plugin bootstrap file and add the following block of code to the top of it, so that our plugin can be activated through the WordPress Plugin activation…