You have to know that child theme functions.php
is loaded before parent theme functions.php
.
It means that inside a child theme functions.php
parent theme classes are not available yet, so you get that fatal error.
If the class is in parent theme functions.php
you can use 'after_setup_theme'
hook to wait for when the parent theme class is defined:
add_action('after_setup_theme', function() {
// assuming class-foo.php is the file that contains your Foo class
require_once get_stylesheet_directory() . '/class-foo.php';
});
However code above may not work because it assumes that the parent theme class is loaded immediately when parent theme functions.php
is loaded, but if that class is loaded using a different hook you have to wait for that hook is fired, instead of 'after_setup_theme'
.
As example, if your parent theme contains something like:
add_action('init', function() {
// assuming class-optimizepress-default-asset.php is the file that contain the class
require_once get_template_directory() . '/class-optimizepress-default-asset.php';
});
you need to wait that 'init'
hook is fired before load your class. In that case you can use the same 'init'
hook with a lower priority:
add_action('init', function() {
require_once get_stylesheet_directory() . '/class-foo.php';
}, 99); // default priority is 10, higher number means lower priority
In summary, there is no a code that works for all classes and all themes, you have to look at parent theme code to understand which is the proper hook to use to be sure parent theme class is available.