カスタム投稿タイプに合わせてブロックエディター用CSSを切り替える

ブロックエディターにcssを適用する

ブロックエディター(Gutenberg)にCSSを適用するには、アクションフックenqueue_block_editor_assetsを利用します。
ブロックエディター全体に共通のスタイルを適用する場合、基本形は以下の通りです。

function my_editor_style() {
  wp_enqueue_style(
    'my-block-editor-style',
    get_template_directory_uri() . '/css/editor-style.css',
    array('wp-edit-blocks'), 
    '1.0.0'
  );
}
add_action('enqueue_block_editor_assets', 'my_editor_style');

カスタム投稿タイプの条件分岐

カスタム投稿タイプに応じてスタイルを切り替えたい場合は、get_current_screen()関数を利用します。
この関数は、管理画面の「現在の画面情報」を取得し、WP_Screen オブジェクトを返します。
基本的な使い方は次の通りです。

$screen = get_current_screen();

if ( $screen->post_type === 'news' ) {
  // カスタム投稿タイプ「news」の画面の時だけ処理
}
  • post_typeのほか、idbase(ベース画面タイプ)、taxonomyなども取得可能です。

最終コード例

カスタム投稿タイプごとにブロックエディター用CSSを切り替える具体例はこちらです。

function my_editor_assets() {
  $screen = get_current_screen();
  if ( $screen && $screen->post_type === 'news' ) {
    wp_enqueue_style('editor-style-news', get_template_directory_uri() . '/css/editor-style-news.css');
  } elseif ( $screen && $screen->post_type === 'column' ) {
    wp_enqueue_style('editor-style-column', get_template_directory_uri() . '/css/editor-style-column.css');
  }
}
add_action('enqueue_block_editor_assets', 'my_editor_assets');

  • get_current_screen()が null になる場合があるため、存在チェック$screen &&を入れると安全です。
  • admin_initより後でないとスクリーンオブジェクトは取得できないことにも注意が必要です。

参考
enqueue_block_editor_assets – フック | Developer.WordPress.org
get_current_screen() – 関数 | Developer.WordPress.org