【自分用メモ・WordPress】カスタム投稿で使用するGutenbergブロックを制限する

自分用メモ。下記のような場合に使用する。

・カスタム投稿を作成した際、「テキストのみ表示させたい」「画像とテキストのみ表示させて、任意のクラスを当てたい」など入力するブロックを制限したい場合がある。

スポンサードサーチ

コード

下記はカスタム投稿を追加するコード。

// カスタム投稿「ニュース」を追加する
add_action( 'init', 'register_news_post_type' );
function register_news_post_type() {
  register_post_type( 'news',
    [
      'label'        => 'ニュース',
      'public'       => true,
      'has_archive'  => true,
      'show_in_rest' => true
  );
}

このコードを下記のように’template’を追加する。

画像ブロックを1つ、段落ブロックを1つの形に制限する。

add_action( 'init', 'register_news_post_type' );
function register_news_post_type() {
  register_post_type( 'news',
    [
      'label'        => 'ニュース',
      'public'       => true,
      'has_archive'  => true,
      'show_in_rest' => true,
      'template'     => [
        [ 'core/image', [
          'className'   => 'news-img',
        ] ],
        [ 'core/paragraph', [
          'className'   => 'news-text',
          'placeholder' => 'ニュースに表示するテキストを入力する',
        ] ],
      ],
      'template_lock' => 'all',
    ],
  );
}

‘template’で使用するブロックを設定する。配列で指定する。

「’core/image’」の部分で使用するブロックを指定。「’className’」で付与するクラスを指定。

「’placeholder’」で入力時に表示しておく

‘template_lock’でブロック操作をできなように設定する。

上記の設定を行うと、下記のようになる。

終わりに

ざっくりとしか調べていないので、後ほど追記する