The get_theme_file_path() WordPress PHP function retrieves the path of a file in the theme.
Usage
$path = get_theme_file_path('file-name.php');
Example:
Input: 'inc/template-functions.php'
Output: /path/to/your/theme/inc/template-functions.php
Parameters
$file(string, optional): File to search for in the stylesheet directory. Default:''
More information
See WordPress Developer Resources: get_theme_file_path()
Examples
Loading a Custom Functions File
Load a custom functions file from the theme directory.
// Load custom-functions.php file from the theme directory.
require get_theme_file_path('custom-functions.php');
Overriding a Parent Theme Function
Allow a child theme to overwrite a function file from the parent theme.
// Load template-functions.php file, allowing child theme to override.
require get_theme_file_path('inc/template-functions.php');
Enqueue a Custom Script
Enqueue a custom JavaScript file from the theme directory.
function my_theme_enqueue_scripts() {
// Enqueue custom-script.js file from the theme directory.
wp_enqueue_script('custom-script', get_theme_file_path('js/custom-script.js'), array(), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');
Register a Custom Widget Area
Register a custom widget area using a PHP file from the theme directory.
function my_theme_register_widget_areas() {
// Register custom-widget-area.php file from the theme directory.
register_sidebar(array(
'name' => 'Custom Widget Area',
'id' => 'custom-widget-area',
'before_widget' => '<div>',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>',
));
require get_theme_file_path('inc/custom-widget-area.php');
}
add_action('widgets_init', 'my_theme_register_widget_areas');
Include a Custom Page Template
Include a custom page template from the theme directory.
function my_theme_custom_page_template($template) {
// Check if the current page has a custom template assigned.
if (is_page_template('custom-page-template.php')) {
// Load custom-page-template.php file from the theme directory.
$template = get_theme_file_path('custom-page-template.php');
}
return $template;
}
add_filter('template_include', 'my_theme_custom_page_template');