1. WordPress

【WordPress】ブロックエディター用のCSSを読み込む方法【add_editor_style】

Share

WordPressでは、ブロックエディター用のCSSを読み込みたいことがあると思います。

できる限り実際の表示に近づけるために、ブロックエディターにもCSSを適用させるのが良いでしょう。

この記事では、ブロックエディター用のCSSを読み込む方法を解説しています。

ブロックエディターにもCSSを適用させたい方は、ぜひ当記事を参考にしてください。

ブロックエディター用のCSSを読み込む方法

ブロックエディター用のCSSを読み込む方法は、ファイル名や階層によって違います。

functions.phpと同じ階層で、ファイル名がeditor-style.cssの場合

editor-style.cssがfunctions.phpと同じディレクトリにある場合のフォルダ構成

ブロックエディター用のCSSファイルがeditor-style.cssというファイル名で、functions.phpと同じ階層にある場合は、以下のように記述します。

functions.php
function my_theme_setup() {

    add_theme_support( 'editor-styles' );
    add_editor_style();

}
add_action('after_setup_theme', 'my_theme_setup' );

add_editor_style関数の第一引数の初期値は'editor-style.css'なので、ファイル名がeditor-style.cssの場合は省略できます。

functions.phpと同じ階層で、ファイル名がeditor-style.cssではない場合

functions.phpと同じディレクトリにあり、ファイル名がeditor.cssの場合のフォルダ構成

エディター用のCSSのファイル名がeditor-style.cssではない場合は、以下のように記述します。

functions.php
function my_theme_setup() {

    add_theme_support( 'editor-styles' );
    add_editor_style( 'editor.css' ); // editor.cssを読み込みたい場合

}
add_action('after_setup_theme', 'my_theme_setup' );

複数のCSSファイルを読み込みたい時

functions.phpと同じディレクトリにあり、editor.cssとstyle.cssがあるの場合のフォルダ構成

複数のCSSをエディターに反映させたいときは、配列を使います。

functions.php
function my_theme_setup() {

    add_theme_support( 'editor-styles' );
    add_editor_style( array( 'editor.css', 'style.css' ) ); // editor.css、style.cssを読み込みたい場合

}
add_action('after_setup_theme', 'my_theme_setup' );

これで複数のCSSをエディターに反映させることができます。

エディター用のCSSが別のディレクトリにある場合

functions.phpとは別のディレクトリにある場合は、相対パスでそのファイルを指定します。

functions.php
function my_theme_setup() {

    add_theme_support( 'editor-styles' );
    add_editor_style( 'assets/css/editor-style.css' );

}
add_action('after_setup_theme', 'my_theme_setup' );

ソースコード

以下はadd_editor_style関数のソースコードです。

wp-includes/theme.php
function add_editor_style( $stylesheet = 'editor-style.css' ) {
	global $editor_styles;

	add_theme_support( 'editor-style' );

	$editor_styles = (array) $editor_styles;
	$stylesheet    = (array) $stylesheet;

	if ( is_rtl() ) {
		$rtl_stylesheet = str_replace( '.css', '-rtl.css', $stylesheet[0] );
		$stylesheet[]   = $rtl_stylesheet;
	}

	$editor_styles = array_merge( $editor_styles, $stylesheet );
}

add_editor_style関数の引数$stylesheetが、グローバル変数である$editor_stylesに追加する処理が行われています。

ブロックエディター用CSSの書き方

ブロックエディター用のCSSは、最適化されて出力されます。

例えば、editor-style.cssに以下のようなCSSが書かれていた場合、

editor-style.css
body {
    background-color: #f0f0f0;
    color: #333;
}

実際に出力されるCSSは以下になります。

.editor-styles-wrapper {
    background-color: #f0f0f0;
    color: #333;
}