Using WordPress ‘get_block_file_template’ PHP filter

The get_block_file_template WordPress PHP filter allows you to modify the block template object after it has been fetched from the theme file.

Usage

add_filter('get_block_file_template', 'your_custom_function', 10, 3);

function your_custom_function($block_template, $id, $template_type) {
    // Your custom code here
    return $block_template;
}

Parameters

  • $block_template (WP_Block_Template|null) – The found block template, or null if there is none.
  • $id (string) – Template unique identifier (example: theme_slug//template_slug).
  • $template_type (string) – Template type: ‘wp_template’ or ‘wp_template_part’.

More information

See WordPress Developer Resources: get_block_file_template

Examples

Add custom template for a specific block

Modify the block template if the template identifier matches a specific value.

add_filter('get_block_file_template', 'custom_block_template', 10, 3);

function custom_block_template($block_template, $id, $template_type) {
    if ($id === 'your-theme-slug//your-template-slug') {
        // Modify the $block_template object here
    }
    return $block_template;
}

Add a fallback template

Provide a fallback template if the $block_template is null.

add_filter('get_block_file_template', 'fallback_block_template', 10, 3);

function fallback_block_template($block_template, $id, $template_type) {
    if ($block_template === null) {
        // Set a fallback $block_template object here
    }
    return $block_template;
}

Change the template based on post type

Modify the block template based on the current post type.

add_filter('get_block_file_template', 'change_template_for_post_type', 10, 3);

function change_template_for_post_type($block_template, $id, $template_type) {
    global $post;

    if ($post->post_type === 'your_post_type') {
        // Modify the $block_template object here
    }
    return $block_template;
}

Modify template for a specific template type

Modify the block template for a specific template type, such as ‘wp_template_part’.

add_filter('get_block_file_template', 'modify_template_type', 10, 3);

function modify_template_type($block_template, $id, $template_type) {
    if ($template_type === 'wp_template_part') {
        // Modify the $block_template object here
    }
    return $block_template;
}

Change template based on user role

Modify the block template based on the current user’s role.

add_filter('get_block_file_template', 'change_template_for_user_role', 10, 3);

function change_template_for_user_role($block_template, $id, $template_type) {
    if (current_user_can('editor')) {
        // Modify the $block_template object for editors
    }
    return $block_template;
}