get_theme_file_uri()WP 4.7.0

Gets the URL of the specified theme file. Takes into account child themes.

The function attempts to find the specified file first in the child theme; if it is not there, it takes it from the parent theme. Thus, the child theme can override the file of the parent theme.

The function works based on two functions:

Does not check for the existence of the file in the parent theme! So if the file is not in the child theme and not in the parent theme, it will still return the URL to the file of the parent/current theme!

This function is great for public themes to ensure child themes work correctly. If you are making a theme just for yourself, you can simply use
get_template_directory_uri() as a micro-optimization.

Use get_parent_theme_file_uri() when you do NOT need to consider the child theme.

Use get_theme_file_path() when you need to get the file path (not URL) in a similar way.

1 time — 0.003745 sec (very slow) | 50000 times — 6.93 sec (fast) | PHP 7.1.5, WP 4.9.4
Hooks from the function

Returns

String. URL of the file.

Usage

get_theme_file_uri( $file );
$file(string)

The name of the file to find in the theme. For example file.js. You can specify a nested file js/file.php or like this /js/file.js.

If the string is left empty, it will return the URL of the active theme, considering the child theme. See get_stylesheet_directory_uri()

Default: ''

Examples

1

#1 Get the URL of the theme file including the child theme

Suppose we want to include the file js/my-script.js in the theme, but we need to make sure that when we create a child theme and the same file in it, the child theme file is included.

Now in WP 4.7 this can be written very simply with the function get_theme_file_uri():

wp_enqueue_script(
	'my-script',
	get_theme_file_uri( 'js/my-script.js' ),
	array(),
	filemtime( get_theme_file_path('js/my-script.js') )
);
0

#2 Does not work if the full path is specified

$path = '/home/example.com/wp-content/themes/mytheme/styles.css';
echo get_theme_file_uri( $path );
// https://example.com/wp-content/themes/mytheme/home/example.com/wp-content/themes/mytheme/styles.css

Changelog

Since 4.7.0 Introduced.

get_theme_file_uri() code WP 7.0

function get_theme_file_uri( $file = '' ) {
	$file = ltrim( $file, '/' );

	$stylesheet_directory = get_stylesheet_directory();

	if ( empty( $file ) ) {
		$url = get_stylesheet_directory_uri();
	} elseif ( get_template_directory() !== $stylesheet_directory && file_exists( $stylesheet_directory . '/' . $file ) ) {
		$url = get_stylesheet_directory_uri() . '/' . $file;
	} else {
		$url = get_template_directory_uri() . '/' . $file;
	}

	/**
	 * Filters the URL to a file in the theme.
	 *
	 * @since 4.7.0
	 *
	 * @param string $url  The file URL.
	 * @param string $file The requested file to search for.
	 */
	return apply_filters( 'theme_file_uri', $url, $file );
}