The resolve_block_template() WordPress PHP function returns the correct ‘wp_template’ to render for the request template type.
Usage
resolve_block_template( $template_type, $template_hierarchy, $fallback_template );
Parameters
$template_type
(string) (Required) – The current template type.$template_hierarchy
(string[]) (Required) – The current template hierarchy, ordered by priority.$fallback_template
(string) (Required) – A PHP fallback template to use if no matching block template is found.
More information
See WordPress Developer Resources: resolve_block_template
Examples
Basic Usage
Retrieve the correct template for a single post.
// Set the template type, hierarchy, and fallback template $template_type = 'single'; $template_hierarchy = array( 'single.php', 'index.php' ); $fallback_template = 'fallback-single.php'; // Get the correct template to render $correct_template = resolve_block_template( $template_type, $template_hierarchy, $fallback_template );
Custom Post Type
Retrieve the correct template for a custom post type ‘portfolio’.
// Set the template type, hierarchy, and fallback template $template_type = 'single-portfolio'; $template_hierarchy = array( 'single-portfolio.php', 'single.php', 'index.php' ); $fallback_template = 'fallback-portfolio.php'; // Get the correct template to render $correct_template = resolve_block_template( $template_type, $template_hierarchy, $fallback_template );
Custom Taxonomy
Retrieve the correct template for a custom taxonomy ‘genre’.
// Set the template type, hierarchy, and fallback template $template_type = 'taxonomy-genre'; $template_hierarchy = array( 'taxonomy-genre.php', 'taxonomy.php', 'archive.php', 'index.php' ); $fallback_template = 'fallback-taxonomy-genre.php'; // Get the correct template to render $correct_template = resolve_block_template( $template_type, $template_hierarchy, $fallback_template );
Custom Archive
Retrieve the correct template for a custom post type archive ‘news’.
// Set the template type, hierarchy, and fallback template $template_type = 'archive-news'; $template_hierarchy = array( 'archive-news.php', 'archive.php', 'index.php' ); $fallback_template = 'fallback-archive-news.php'; // Get the correct template to render $correct_template = resolve_block_template( $template_type, $template_hierarchy, $fallback_template );
Page Template
Retrieve the correct template for a specific page template ‘custom-page’.
// Set the template type, hierarchy, and fallback template $template_type = 'page'; $template_hierarchy = array( 'custom-page.php', 'page.php', 'index.php' ); $fallback_template = 'fallback-page.php'; // Get the correct template to render $correct_template = resolve_block_template( $template_type, $template_hierarchy, $fallback_template );