The get_template_part WordPress PHP action fires before an attempt is made to locate and load a template part.
Usage
add_action('get_template_part', 'your_custom_function', 10, 4);
function your_custom_function($slug, $name, $templates, $args) {
// Your custom code here
}
Parameters
$slug: string – The slug name for the generic template.$name: string – The name of the specialized template.$templates: string[] – Array of template files to search for, in order.$args: array – Additional arguments passed to the template.
More information
See WordPress Developer Resources: get_template_part
Examples
Log template parts
Log template parts that are being loaded.
add_action('get_template_part', 'log_template_parts', 10, 4);
function log_template_parts($slug, $name, $templates, $args) {
// Log template parts
error_log("Slug: $slug, Name: $name");
}
Modify template search order
Change the template search order for a specific template part.
add_action('get_template_part', 'modify_template_search_order', 10, 4);
function modify_template_search_order($slug, $name, $templates, $args) {
if ($slug == 'specific_template_slug') {
// Modify the templates array
$templates = array_reverse($templates);
}
}
Add custom template directory
Add a custom template directory for a specific template part.
add_action('get_template_part', 'add_custom_template_directory', 10, 4);
function add_custom_template_directory($slug, $name, $templates, $args) {
if ($slug == 'custom_template_slug') {
// Add a custom template directory to the search order
array_unshift($templates, 'path/to/custom/template/directory/');
}
}
Filter template based on user role
Load a different template for users with a specific role.
add_action('get_template_part', 'filter_template_based_on_user_role', 10, 4);
function filter_template_based_on_user_role($slug, $name, $templates, $args) {
if ($slug == 'template_slug' && current_user_can('specific_role')) {
// Change the template for users with a specific role
$name = 'different_template_name';
}
}
Add a custom template part
Add a custom template part before the main template part.
add_action('get_template_part', 'add_custom_template_part', 10, 4);
function add_custom_template_part($slug, $name, $templates, $args) {
if ($slug == 'main_template_slug') {
// Load the custom template part
get_template_part('custom_template_slug', 'custom_template_name');
}
}