Using WordPress ‘block_template_part()’ PHP function

The block_template_part() WordPress PHP function is used to print a specific block template part such as “header” or “footer”.

Usage

To use block_template_part(), simply pass in the name of the block template part you want to print as a string.

block_template_part('header');

The above example will print the ‘header’ block template part.

Parameters

  • $part (string) – The block template part to print. Commonly used with values like “header” or “footer”.

More information

See WordPress Developer Resources: block_template_part()

This function is used in block themes and does not output any parameters added to the template part itself. If you’re adding a template part inside a HTML block template with parameters, using block_template_part() to output the same part in a PHP template will not output the wrapping element or CSS class.

Examples

Printing the Header Template Part

The following code will print the ‘header’ block template part.

block_template_part('header');

The following code will print the ‘footer’ block template part.

block_template_part('footer');

Checking if a Template Part Exists Before Printing

The following code checks if a ‘sidebar’ template part exists before printing it.

if ( does_block_template_part_exist('sidebar') ) {
    block_template_part('sidebar');
}

Using in a Loop

You can use block_template_part() inside a loop to print a template part for each post.

while ( have_posts() ) {
    the_post();
    block_template_part('content');
}

Using in a Conditional Statement

You can use block_template_part() inside a conditional statement to print different template parts based on a condition.

if ( is_front_page() ) {
    block_template_part('front-page-header');
} else {
    block_template_part('header');
}

In the last example, if the page is the front page, it prints the ‘front-page-header’ block template part. For all other pages, it prints the ‘header’ block template part.