Autoloading in Child Theme

I’m trying to autoload the vendor/autoload.php from my parent theme into my child theme.

heres what i have tried but to no avail:

function beast_theme_setup() {
  $var1 = get_theme_root_uri() . '/beast/vendor/autoload.php';
  $var2 = get_theme_root_uri() . '/beast/functions.php';
  $var = locate_template( array( $var1, $var2), true, false );
  var_dump($var);
}

add_action( 'after_setup_theme', 'beast_theme_setup', 11 );

and

include get_theme_root_uri() . '/beast/vendor/autoload.php';

Any help on this would be amazing.

Thanks Jake.

1
1

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