What is the best way to instantiate a class of a plugin in your WordPress theme?

There are two common solutions to access classes in a plugin from inside a theme:

1. Use an autoloader in the plugin (preferred).

You tell the autoloader how to relate a class name to a PHP file name that contains the class. Then, when you access a class that is not yet known to PHP, the autoloader checks for the file that relates to that class and loads it.

An easy way to use an autoloader is through Composer, but without any additional setup, this will bump your PHP requirement to PHP5.3.2+.

More details on Composer autoloading: https://getcomposer.org/doc/01-basic-usage.md#autoloading

2. Use a function to retrieve an instance.

You can provide one function that returns a reference to an instance of your plugin’s class.

Your theme can then check whether that function exists and retrieve the needed reference. After it has access to that reference, it can use the class as if it was within the plugin.

General notes.

As with most things in WordPress, you need to make sure that you correctly manage the WordPress lifecycle. If code from the plugin is only executed on a specific WP action, you must make sure that your theme only references that code after the corresponding action has been triggered.

Leave a Comment