By default, a WordPress custom post type does not use the Gutenberg editor. Why? In this quick tip, I’ll walk you through the why and show you how to enable the Gutenberg editor for your custom post types. Don’t worry. It’s literally one configuration parameter.
Gutenberg uses the REST API. But by default, the REST API parameter turned off when you register a custom post type. Therefore, you need to intentionally turn it on in your code. Let me show you how.
The Code
Here is a link to the Books plugin gist if you want to work along with me.
In the configuration arguments where you register the custom post type, add the following configuration parameter:
'show_in_rest' => true, // To use Gutenberg editor.
For example, let’s say you are registering a Book post type. The registration arguments might be:
function prefix_register_book_post_type() {
$labels = [
// left out for brevity.
];
$args = [
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_rest' => true, // To use Gutenberg editor.
'query_var' => true,
'rewrite' => [ 'slug' => 'book' ],
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
];
register_post_type( 'book', $args );
}
Go Deeper
Want to go deeper into custom post types? Check out these resources:
Alvina says
Hey Tonya, I am trying to enable Gutenberg editor for custom post types and having an error. Can you help me resolve this error? I am having in this line of code:
I have seen this code here https://www.cloudways.com/blog/gutenberg-wordpress-custom-post-type/
Tonya Mork says
Hello Alvina,
This article gives you the details of how to enable Gutenberg for your
portfolio
custom post type. Essentially, you need to set the'show_in_rest'
argument totrue
.Next, you need to register the custom post type after WordPress fires the
'init'
action event. That means your code above needs to be fired from a callback that is registered to the'init'
action event, i.e. hook into'init'
. For example:But wait, there’s more that you need to do. For WordPress to add the endpoints for the portfolio, you’ll need to flush the rewrite rules when activating the plugin that registers your portfolio cpt. How do you do that? I recommend that you check out this hands-on coding lab to learn more about registering custom post types.
Cheers,
Tonya