Autoloading in Child Theme

So there are one or two things to keep in mind:

  • There should only be 1 vendor folder
  • There should be a primary composer.json that’s in your project root, that would pull in all the dependencies
  • You always check for and load the autoloader in the current directory, there’s no guarantee it is or isn’t there as you may or may not be a dependency yourself

But importantly, there’s more information about WP themes you need to know that simplify your task:

Firstly, get_theme_root isn’t necessary, you can use get_template_directory() instead, and it will give you the parent theme directory, so no hardcoding the parent themes name.

This should simplify your code to this:

if ( file_exists( get_template_directory() . '/vendor/autoload.php' ) ) {
    require get_template_directory() . '/vendor/autoload.php';
}

But even this isn’t necessary, which brings us to the second piece of information:

In WordPress, the child themes functions.php is loaded, then the parent themes functions.php immediately afterwards.

So all you need to do is make sure that the parent theme loads the autoloader, and that all your code is ran on actions as it should be ( except the autoloader itself ). This way you don’t need to load the parent themes autoloader at all, it will do it itself

Leave a Comment