Using WordPress ‘get_theme_file_uri()’ PHP function

The get_theme_file_uri() WordPress PHP function retrieves the URL of a file in the theme. It searches in the stylesheet directory before the template directory, allowing themes that inherit from a parent theme to override a single file.

Usage

To use the function, simply provide the file path within your theme as the argument:

get_theme_file_uri('/path/to/your/file.ext');

Parameters

  • $file (string, optional): The file to search for in the stylesheet directory. Default is an empty string.

More information

See WordPress Developer Resources: get_theme_file_uri()

Examples

Enqueue a CSS file

Enqueue a custom Font Awesome CSS file stored in your theme’s CSS directory:

wp_enqueue_style('custom-font-awesome', get_theme_file_uri('/css/all.min.css'), array());

Display a theme image in a block pattern

Include a local theme asset (e.g., an image) in your block pattern:

<figure class="wp-block-image size-full">
    <img src="<?php echo esc_url(get_theme_file_uri('assets/img/my-asset.png')); ?>"
         alt="<?php _e('Asset description'); ?>"
         width="640"
         height="400"/>
</figure>

Enqueue a JavaScript file

Enqueue a custom JavaScript file stored in your theme’s js directory:

wp_enqueue_script('custom-script', get_theme_file_uri('/js/custom-script.js'), array(), '1.0', true);

Add a theme favicon

Add a favicon to your theme’s head section using the wp_head action:

function my_theme_add_favicon() {
    echo '<link rel="shortcut icon" href="' . esc_url(get_theme_file_uri('/assets/img/favicon.ico')) . '" />';
}
add_action('wp_head', 'my_theme_add_favicon');

Add a background image

Add a background image to a div element using inline CSS:

<div style="background-image: url('<?php echo esc_url(get_theme_file_uri('/assets/img/background.jpg')); ?>');">
    <!-- Your content here -->
</div>