Filtering customTemplates from theme.json with a plugin

Recently I was rebuilding the Helpful Digital intranet using a WordPress block theme called UniBlock. As part of this I had written a custom plugin to register a new post type and meta fields. This was all very straightforward, until I realised that the lovely templates included in the theme couldn’t be applied to the new post type.

I’m not as familiar with block themes as traditional ones, but I have been developing for WordPress for a long time. Working this out, or more specifically working out what I needed to look for, was one of the more painful experiences I’ve had with WordPress. Web searches and direct searches of the largely excellent developer codex led me down a very long rabbit hole, to reading class definitions, that finally led me to the right filter ‘wp_theme_json_data_theme’. This filter actually lets you modify a lot more than just the customTemplates data, and there are also others to filter data from WordPress (wp_theme_json_data_default), blocks (wp_theme_json_data_blocks), and user (wp_theme_json_data_user).

Working with these filters is easy once you know how – the WP_Theme_JSON_Data class provides a update_with() function that overlays the new data as long as you provide a valid structure and declare the version. Knowing what to look for, I then found a nice example in a WordPress 6.1 feature announcement blog post ‘Filters for theme.json data’

Finally here’s a quick code example of adding support for your custom post type to one of the templates declared in a block theme’s theme.json:


function filter_theme_json_templates( $theme_json ){
    $customTemplates = $theme_json->get_data()['customTemplates'];
    foreach ( $customTemplates as $key => $template ) {
        if ( $template['name'] === 'single-full' ) {
            array_push( $template['postTypes'], 'task' );
            $customTemplates[ $key ] = $template;
        }
    }
    $new_data = [ 'version' => 2, 'customTemplates' => $customTemplates ];

    return $theme_json->update_with( $new_data );
}
add_filter( 'wp_theme_json_data_theme', 'filter_theme_json_templates' );

Category:

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *