Including a file in a WordPress template

If you want to call a file within a temple in WordPress, it is recommend to use get_template_part() instead of the PHP include() function. get_template_part() provides a simple mechanism for child themes to overload reusable sections of code in the theme.

Use get_template_part() to include a file in a template

Syntax

get_template_part( $slug, $name = null );

It first loads the template “{slug}-{name}.php” if $name is not empty. If $name is empty or the template “{slug}-{name}.php” does not exist, it loads “{slug}.php”. If “{slug}.php” still does not exist, no file will be included. Note you won’t get warnings if it fails to find any matching file.

Examples

Below example includes a navigation bar in the header.php template file.

get_template_part( 'template-parts/navigation/navigation', 'nav-bar' );

In the case of a child theme is being used, assuming that the parent theme is twentynineteen, and the child theme is twentynineteen-child, the code above includes the first existing file among these files in this priority:

  1. wp-content/themes/twentynineteen-child/template-parts/navigation/navigation/nav-bar.php
  2. wp-content/themes/twentynineteen/template-parts/navigation/navigation/nav-bar.php
  3. wp-content/themes/twentynineteen-child/template-parts/navigation/navigation/nav-bar.php
  4. wp-content/themes/twentynineteen/template-parts/navigation/navigation/nav-bar.php

Using include() to include a file in a template

If you still want to directly include a file using include_once() or require_once(), see below examples.

Example 1: Include a file from the parent theme

If a child theme is being used, get_template_directory() returns the absolute path of the parent theme.

require_once( get_template_directory() . '/inc/my-functions.php' );

Example 2: Include a file from the child theme

If a child theme is being used, get_stylesheet_directory() returns the absolute path of the child theme.

require_once( get_stylesheet_directory() . '/inc/my-functions.php' );