Adding a Block Template to a CPT

If you have a WordPress website with an existing custom post type and you want to add a Gutenberg block template to be used for every new post of this custom post type there are two ways of doing this.

If you can access the code that registers the post type, you can just add template as an argument in that code. You can see more about how to do that in the WordPress developer documentation for example.

If you can’t access the code that registers the post type you can still add arguments to it, including an argument to add a block template to new posts of that custom post type, with the register_post_type_args filter. See here below:

add_filter( 'register_post_type_args', 'bw_change_cpt', 10, 2 );
function bw_change_cpt( $args, $post_type ){
 
    if( $post_type == 'portfolio' ){
        $args['template'] = [['core/post-featured-image']];
    }
 
    return $args;
}

Now, if you were to click on Add New under Portfolio on this WordPress website, you would see a new post with a block for a featured image already in place.

I’ve named the function bw_change_cpt but you can name it whatever you want of course, just make sure you are consistent with it, it’s referenced in two places, so you’ll need to change both. And check to make sure you have the correct name for the custom post type. The one in this example is called portfolio, if yours is called differently be sure to change that.

For an example of how to add more or different blocks, or how to set parameters for a block, you can also look at the WordPress developer documentation, but this elegant themes article also has a few good tips under Method 3 and A White Pixel has some good examples too.

Leave a Comment