Creating a block-based theme Category page template for Custom Post Types

I’ve been experimenting with building block-based themes. In order to create a category page template you would create a /block-template directory and add a category.html file. Then you can jump into the block editor, drop in whatever blocks you want to use, go to the code editor, copy the code and paste that into the category.html file.

Now, the key to all of this is that one of the blocks you use when creating the template is the core Query loop block. You’ll then set it to ‘Inherit query from URL’:

That’s it, you’ve got a category page template that displays the posts of whatever category the current url is showing.

The category page template doesn’t work for Custom Post Types

That’s right, I tried using the core Query loop block, but the categories of the custom post type would not display.

Why is that? Because custom post types are excluded from the main query by default. Thank you Pieter Goosen for your very helpful StackOverflow assist.

At any rate, to include the custom post type in the main query, you just need to use the pre_get_posts hook, here’s a code snippet of what that could look like straight from Pieter’s StackOverflow:

function custom_post_type_cat_filter($query) {
  if ( !is_admin() && $query->is_main_query() ) {
    if ($query->is_category()) {
      $query->set( 'post_type', array( 'post', 'YOUR CPT' ) );


43 thoughts on “Creating a block-based theme Category page template for Custom Post Types

Comments are closed.