Gutenberg offers an intuitive drag-and-drop content creation interface, enabling real-time customization. By defining block templates for your CPT, you guide users in structuring their content, reducing errors and ensuring consistent formatting.
Defining the template in a custom post type
You can also define a predefined block template that the user will see when creating new content for this CPT. This is done with the template
argument when you register the CPT.
Here’s an example where you define a block template for the CPT portfolio
:
function create_portfolio_cpt() {
$labels = array(
'name' => 'Portfolios',
'singular_name' => 'Portfolio',
);
$args = array(
'label' => 'Portfolios',
'public' => true,
'show_in_rest' => true,
'supports' => array('title', 'editor', 'thumbnail', 'revisions', 'custom-fields'),
'has_archive' => true,
'rewrite' => array('slug' => 'portfolio'),
'template' => array( // Defining block templates
array('core/heading', array(
'level' => 2,
'placeholder' => 'Add a heading',
)),
array('core/paragraph', array(
'placeholder' => 'Add a description',
)),
array('core/image', array(
'align' => 'center',
)),
),
'template_lock' => 'all', // Prevents basic blocks from being deleted
);
register_post_type('portfolio', $args);
}
add_action('init', 'create_portfolio_cpt');
Explanation of options :
template
: An array containing the default blocks that will be inserted when the user creates new content for this CPT.template_lock
: Can be set to'all'
or'insert'
:'all'
: The user can neither modify nor delete defined blocks.'insert'
: The user can modify the content of blocks, but not delete them or add new ones.
Create a template on an existing CPT
You can use WordPress filters to add block templates to an existing CPT. To do this, you can use the register_post_type_args
filter to add a block template when the CPT is registered.
Example of code to add to your functions.php
file:
xxxxxxxxxx
function add_custom_template_to_cpt($args, $post_type) {
// Replace 'portfolio' with your CPT slug
if ($post_type === 'portfolio') {
$args['template'] = array(
array('core/heading', array('level' => 2, 'placeholder' => 'Titre')),
array('core/paragraph', array('placeholder' => 'Description')),
array('core/image', array('align' => 'center')),
);
$args['template_lock'] = 'all'; // Prevents users from modifying or deleting default blocks
}
return $args;
}
add_filter('register_post_type_args', 'add_custom_template_to_cpt', 10, 2);