Getting the current WordPress theme directory URI with get_template_directory_uri

The get_template_directory_uri function in WordPress returns the URI of the current theme’s directory. This can be useful for accessing resources such as images, stylesheets, or JavaScript files that are located within the theme’s directory. By using this function, developers can easily reference theme-specific files without hardcoding the directory path, making their code more flexible and portable.

Parameters and Return Value of get_template_directory_uri Function

The get_template_directory_uri function does not accept any parameters.

When called, the function returns a string value that represents the URI to the active theme’s template directory.

Examples

How to get the template directory URI

Use the get_template_directory_uri function to retrieve the URI of the current theme’s directory.

$theme_uri = get_template_directory_uri();
echo $theme_uri;

How to enqueue a script using the template directory URI

Use the get_template_directory_uri function to enqueue a script with the URI of the current theme’s directory.

function enqueue_custom_script() {
 wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_custom_script' );

How to include a template part using the template directory URI

Use the get_template_directory_uri function to include a template part with the URI of the current theme’s directory.

get_template_part( 'template-parts/content', 'page', array( 'uri' => get_template_directory_uri() ) );

Conclusion

In conclusion, the get_template_directory_uri function is an essential tool for WordPress developers looking to efficiently retrieve the directory URI of the current theme. By utilizing this function, developers can easily access theme assets such as stylesheets, scripts, and images, improving the overall performance and organization of their WordPress projects. With its simple syntax and powerful functionality, get_template_directory_uri is a valuable resource for any developer working with WordPress themes.

Related WordPress Functions