{dynamic}_template_path
> **Note:** This is a dynamic hook. The actual hook name is constructed at runtime. Filters the director path to the template file This can be used for template overrides by modifying the path to go to a directory in the theme or another plugin. Filters the template file path, allowing for theme or plugin overrides before the template is loaded.
add_filter( '{dynamic}_template_path', $callback, 10, 2 );
Description
This dynamic filter hook allows developers to override plugin template paths. By modifying the `$templates_directory` and `$file_name` parameters, you can point to custom template files within your theme or another plugin. This is ideal for extensive template customizations without altering core plugin files.
Usage
add_filter( '{dynamic}_template_path', 'your_function_name', 10, 2 );
Parameters
-
$templates_directory(string) - Path to the plugins template folder
-
$file_name(string) - The file name of the template file
Return Value
The filtered value.
Examples
/**
* Example of how to override a plugin's template path.
*
* This function hooks into the plugin's _template_path filter and checks if
* a custom template file exists in the theme's directory. If it does, it
* returns the path to the theme's template file; otherwise, it falls back
* to the plugin's default template path.
*/
add_filter( 'your_plugin_prefix_template_path', function( $templates_directory, $file_name ) {
// Construct the potential path to the template in the theme's directory.
// We assume templates are in a 'your-plugin-name/templates/' subdirectory within the theme.
$theme_template_path = trailingslashit( get_stylesheet_directory() ) . 'your-plugin-name/templates/' . $file_name;
// Check if the custom template file exists in the theme.
if ( file_exists( $theme_template_path ) ) {
// If it exists, return the path to the theme's template.
return trailingslashit( get_stylesheet_directory() ) . 'your-plugin-name/templates/';
}
// If the custom template doesn't exist in the theme, return the original plugin template path.
return $templates_directory;
}, 10, 2 );
Placement
This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.
Source Code
src/utilities.php:442
public static function get_template( $file_name ) {
$templates_directory = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR;
/**
* Filters the director path to the template file
*
* This can be used for template overrides by modifying the path to go to a directory in the theme or another plugin.
*
* @param string $templates_directory Path to the plugins template folder
* @param string $file_name The file name of the template file
*
* @since 1.0.0
*/
$templates_directory = apply_filters( self::get_prefix() . '_template_path', $templates_directory, $file_name );
$asset_path = $templates_directory . $file_name;
return $asset_path;
}