The get_block_templates WordPress PHP filter allows you to modify the array of queried block templates after they’ve been fetched.
Usage
add_filter( 'get_block_templates', 'your_custom_function', 10, 2 ); function your_custom_function( $query_result, $query ) { // your custom code here return $query_result; }
Parameters
- $query_result (WP_Block_Template[]): Array of found block templates.
- $query (array): Arguments to retrieve templates.
- slug__in (array): List of slugs to include.
- wp_id (int): Post ID of customized template.
- $template_type (string): ‘wp_template’ or ‘wp_template_part’.
More information
See WordPress Developer Resources: get_block_templates
Examples
Exclude specific template slugs
Exclude ‘header’ and ‘footer’ from the block templates array.
add_filter( 'get_block_templates', 'exclude_template_slugs', 10, 2 ); function exclude_template_slugs( $query_result, $query ) { $excluded_slugs = array( 'header', 'footer' ); return array_filter( $query_result, function( $template ) use ( $excluded_slugs ) { return ! in_array( $template->slug, $excluded_slugs ); } ); }
Add a custom template to the array
Add a custom template to the block templates array.
add_filter( 'get_block_templates', 'add_custom_template', 10, 2 ); function add_custom_template( $query_result, $query ) { $custom_template = new WP_Block_Template( array( 'slug' => 'custom-template', 'title' => 'Custom Template', ) ); $query_result[] = $custom_template; return $query_result; }
Filter templates by custom property
Filter block templates that have a ‘custom’ property set to true.
add_filter( 'get_block_templates', 'filter_custom_property_templates', 10, 2 ); function filter_custom_property_templates( $query_result, $query ) { return array_filter( $query_result, function( $template ) { return isset( $template->custom ) && $template->custom; } ); }
Order templates alphabetically
Order block templates alphabetically by their title.
add_filter( 'get_block_templates', 'order_templates_alphabetically', 10, 2 ); function order_templates_alphabetically( $query_result, $query ) { usort( $query_result, function( $a, $b ) { return strcmp( $a->title, $b->title ); } ); return $query_result; }
Limit the number of templates
Limit the number of block templates to 5.
add_filter( 'get_block_templates', 'limit_template_number', 10, 2 ); function limit_template_number( $query_result, $query ) { return array_slice( $query_result, 0, 5 ); }