Using WordPress ‘get_template_part_{$slug}’ PHP action

The get_template_part_{$slug} WordPress PHP action fires before the specified template part file is loaded.

Usage

add_action('get_template_part_example', 'custom_function', 10, 3);

function custom_function($slug, $name, $args) {
    // your custom code here
}

Parameters

  • $slug (string): The slug name for the generic template.
  • $name (string|null): The name of the specialized template.
  • $args (array): Additional arguments passed to the template.

More information

See WordPress Developer Resources: get_template_part_{$slug}

Examples

Adding custom markup before a template part

This example adds a custom div element with a class name “pre-template” before loading the ‘content’ template part.

add_action('get_template_part_content', 'add_pre_template_markup', 10, 3);

function add_pre_template_markup($slug, $name, $args) {
    echo '<div class="pre-template">This is added before the template part</div>';
}

Logging the template part being loaded

This example logs the template part being loaded to a custom log file.

add_action('get_template_part_content', 'log_template_part', 10, 3);

function log_template_part($slug, $name, $args) {
    error_log("Template part loaded: {$slug}-{$name}");
}

Modifying the global post object

This example modifies the global post object’s title before loading the ‘content’ template part.

add_action('get_template_part_content', 'modify_post_title', 10, 3);

function modify_post_title($slug, $name, $args) {
    global $post;
    $post->post_title = 'Modified: ' . $post->post_title;
}

Adding a custom attribute to a template part

This example adds a custom data attribute to the ‘content’ template part.

add_action('get_template_part_content', 'add_custom_data_attribute', 10, 3);

function add_custom_data_attribute($slug, $name, $args) {
    echo 'data-custom-attr="example"';
}

Conditionally loading a different template part

This example loads a different template part ‘content-special’ instead of the default ‘content’ template part based on a condition.

add_action('get_template_part_content', 'conditionally_load_special_template', 10, 3);

function conditionally_load_special_template($slug, $name, $args) {
    if (is_singular('post')) {
        get_template_part('content', 'special');
        exit;
    }
}