Include files in child theme functions file

Typically in my theme function file I’ll require other files to keep things neat.

require_once("foo.php");

Now working in a child theme I’d like to do that same. I’m adding custom admin options and it seems impossible to include code. I’ve echoed out the path to make sure I’m calling the right file and it is calling the proper location but nothing inside that file seems to run. The code runs fine if placed inside the child theme functions file.

Related posts

Leave a Reply

8 comments

  1. Child themes reference parent themes by directory name, and in a normal install all your themes live in wp-content/themes/, so I’d say it’s fine to reference those themes by their relative path:

    include '../parent-theme/some-file.php';
    

    If that makes you uncomfortable, I observe the following constants in WordPress 3.0.1 with a twentyten child theme called tt-child:

    TEMPLATEPATH     /home/adam/public_html/wp3/wp-content/themes/twentyten
    STYLESHEETPATH   /home/adam/public_html/wp3/wp-content/themes/tt-child
    

    So you can do the following in your child theme to reference the parent theme directory:

    include TEMPLATEPATH . '/some-file.php';
    
  2. In a child theme the proper way is

    require_once( get_stylesheet_directory() . '/foo.php');
    

    While in the parent theme you can still use

    require_once ( get_template_directory() . '/foo.php' );
    

    get_template_directory() still works in the child theme, sadly target the parent theme directory. In your case it’s useful

  3. You definitely do not want to hard code the URL. The proper way of doing so is

    require_once( get_stylesheet_directory(). '/my_included_file.php' );
    

    See more info at WordPress Codex

    Now, if your e.g. modifying header.php which has an include you would reference it as follows:

    require_once( get_stylesheet_directory() . '/../parenthteme/my_included_file.php' );
    
  4. Hi @curtismchale:

    Don’t know if this is it or not, but you need to include quotes around foo.php, like so:

    require_once('foo.php');
    

    Does that solve your problem?

  5. The simplest and the best way to require files in either the theme’s functions.php or in plugins development is by using dirname(__FILE__).

    In your case just needed this:

    require_once dirname(__FILE__)."/foo.php";
    

    If the file you want to require is on another folder, inc for example, you would say this:

    require_once dirname(__FILE__)."/inc/foo.php"; 
    

    Hope this will help someone in future.

  6. It is completely possible and normal to do includes in functions.php.

    I do it like this in my child theme (php is subdirectory for code):

    include 'php/core.php';
    

    If you have issues without apparent reason try enabling debug mode in wp-config.php:

    define('WP_DEBUG', true);
    

    There might be relevant errors happening, but not displayed.