0

I want to setup a gutenberg screen with one block only. I know I can hide the add block button with CSS with this code:

.block-editor-inserter {
    display: none;
}

How can I hide the button with a hook/filter? Hiding with css is not ideal because the selectors may change in the future.

enter image description here

2
  • 1
    Have you considered making a custom post type for this one screen, and then adding a block template? You can lock the template so it adds that single block and does not allow users to add, move, or delete blocks.
    – WebElaine
    Mar 5, 2020 at 14:22
  • @WebElaine it is custom post type. How can lock the template to have one block and not allow add move or delete blocks?
    – BenB
    Mar 5, 2020 at 15:11

1 Answer 1

1

You can register a template for your CPT and lock that template so users cannot add, move, or delete blocks.

There are several ways to set up the template, but since your CPT is already registered, the easiest might be:

<?php
add_action( 'init', 'wpse_360075_register_block_template' );
function wpse_360075_register_block_template() {
    // Make sure to change "yourcptslug" to your CPT slug
    $post_type_object = get_post_type_object( 'yourcptslug' );
    // Here is the template - change it to whatever single block you like
    $post_type_object->template = array(
        array( 'core/paragraph', array() ),
    );
    // This locks the template
    $post_type_object->template_lock = 'all';
}
?>

As long as you substitute in your actual CPT slug, and whichever block you want added, this will ensure that any new posts in this CPT will have only the template block and won't allow users to remove it or add other blocks. (If you already have existing posts published in this CPT, you would have to delete them as the template only applies to new posts.)

1
  • Worked like a charm. Thanks!
    – BenB
    Mar 5, 2020 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.