Load parent theme files before child theme functions.php

I am creating a theme framework to use in future wordpress themes that I develop. I would like to include dependant files such as classes inside the parent theme before the child theme functions.php gets loaded. This way the child theme doesn’t need to include the classes.

I’ll try to show an example:

Read More

parent-theme – file.php:

require_once get_template_directory().'/classes/Core.php';
require_once get_template_directory().'/classes/Core_View.php';
$CoreView = new Core_View();
$CoreView->init();

child-theme – functions.php:

require_once get_template_directory().'/classes/ContentSidebarView.php';
$ContentSidebarView = new ContentSidebarView();
$ContentSidebarView->init();

ContentSidebarView Class file:

Class ContentSidebarView extends Core_View{

    public function init(){
        // Do Something
    }

}

Currently, I get an error that class Core_View is not found when I use the child theme. This isn’t the case if I just use the parent theme.

What I’d Like:
I would like to require only the template in the child theme and initiate it. This means that the Core_View would have to already be loaded.

I am also open to suggestions as to how to initiate the template. Maybe it would be better in the child theme index file?

Related posts

2 comments

  1. The functions.php file executes at plugins_loaded, with the Child Theme functions.php executing before the Parent Theme functions.php. That means that, in order to load functional sub-files in the Child Theme after the Parent Theme functions.php executes, you simply need to hook your include() calls after plugins_loaded.

    A usually safe action for such purposes is after_setup_theme:

    function wpse130681_load_dependent_functional_files() {
        require_once get_template_directory().'/classes/ContentSidebarView.php';
        $ContentSidebarView = new ContentSidebarView();
        $ContentSidebarView->init();
    }
    add_action( 'after_setup_theme', 'wpse130681_load_dependent_functional_files' );
    

    That said: if you’re running into issues such as this one, you’re probably doing something wrong in the first place. Just guessing from your code sample:

    1. Hook your class instantiation into an appropriate hook, such as init
    2. Make your framework classes extensible via filters, and extend in your Child Theme via those filters.
  2. Provide a custom action in your parent theme:

    do_action( get_template() . '_loaded', $api_class_instance );
    

    In your child theme, run the first code on that hook, not earlier:

    add_action( get_template() . '_loaded', function( $api_class_instance ) {
        $api_class_instance->some_public_method();
    });
    

Comments are closed.