この記事は最後に更新してから1年以上経過しています。

Gutenbergエディターのフォントを変える

説明

Gutenbergエディターを試していてしっくりこないのが、編集時とそれを投稿した際の見た目の違い。GutenbergエディターとテーマTwenty Seventeenとではまったく異なるタイプのフォントが適用されていることが大きな理由である。

font-familyの違いを確認

まずはそれぞれにどんなフォントが指定されているのか確認していこう。Gutenbergエディターでは編集要素が細分化されているが、デモページで多数出現するタイトルと本文部分のfont-familyはどちらも「"Noto Serif",serif」が指定されている。

// 以下font-familyのみ抜粋
.editor-post-title__block .editor-post-title__input {
    font-family: "Noto Serif",serif;
}

.editor-block-list__block {
    font-family: "Noto Serif",serif;
}

これに対してテーマTwenty Seventeenでは、主要部分のfont-familyが「sans-serif」となっている(要素別に個別指定もある)。

Twenty Seventeenの主要部分は「sans-serif」
// 以下font-familyのみ抜粋
html {
    font-family: sans-serif;
}

Gutenbergエディターのfont-familyを変える

異なる系統のfont-familyが指定されていることがわかったところで、Gutenbergエディターの指定を変更し、「しっくりこない」感を緩和しようと思う。Gutenbergエディターのcssを調整する際に利用できるアクションはいくつか存在しているが、ここではGutenbergエディター自身がJavaScriptやCSSファイルの読み込みを行うgutenberg_editor_scripts_and_styles関数(/gutenberg/lib/client-assets.php)が最後に実行するenqueue_block_editor_assetsアクションを利用する。テーマのfunctions.php向けのサンプルは次の通り。

add_action( 'enqueue_block_editor_assets', 'set_mytheme_font_family' );

function set_mytheme_font_family() {
	$inline =
".gutenberg-editor-page .editor-post-title__block,
.gutenberg-editor-page .editor-post-title__input,
.gutenberg-editor-page .editor-block-list__block {
    font-family: %s;
}";
	wp_add_inline_style( 'wp-edit-post', sprintf( $inline, 'sans-serif' ) );
}

Gutenbergエディターの表示は次のように変わる。

Gutenbergエディターのタイトルと共通ブロックに「sans-serif」を適用

フォントサイズや領域の違いはあるが、違和感はかなり和らいだと思う。

おまけ

さてgutenberg_editor_scripts_and_styles関数の中身を見てみると、block_editor_settingsフィルターが気になった。

$editor_settings = apply_filters( 'block_editor_settings', $editor_settings, $post );

パラメータ$editor_settingsは連想配列で、エディターに関連するさまざまな設定を調整できるようになっている。

キー内容
alignWidefalse
availableTemplates連想配列(キーがテンプレートファイル名、値がテンプレート名)
allowedBlockTypestrue
disableCustomColorsfalse)
disablePostFormatsfalse
titlePlaceholder"タイトルを追加"
bodyPlaceholder"本文をここに書く"
isRTLfalse
autosaveInterval10
maxUploadFileSize※環境依存値
allowedMimeTypes連想配列(キーがファイル拡張子、値がそのMIMEタイプ名)
stylesスタイル要素を含んだ配列

$editor_settingsの内容はこのフィルターの実行後にインラインスクリプトとして出力されるようになっており、Gutenbergエディターをカスタマイズする際には活用できそうだ。


最終更新 : 2018年10月16日 13:17


お勧め

get_post_time(2018年5月27日 更新)

mixed get_post_time( [ string $d = 'U' [ , bool $gmt = false [ , mixed $post = null [ , bool $translate = false ] ] ] ] )
パラメータ$dで指定されたフォーマットに従って投稿データの投稿時刻を取得する。

has_tag(2012年1月17日 更新)

bool has_tag( [ mixed $tag = '' [ , mixed $post = null ] ] )
投稿記事に投稿タグが付属しているか調べる。

delete_term_meta(2018年5月27日 更新)

bool delete_term_meta( int $term_id, string $meta_key [ , mixed $meta_value = '' ] )
タームのメタ情報を削除する。

wp_save_post_revision(2023年4月3日 更新)

int | WP_Error | void wp_save_post_revision( int $post_id )
現状の投稿のリビジョンを作成する。

safecss_filter_attr(2023年3月31日 更新)

string safecss_filter_attr( string $css [ , string $deprecated = '' ] )
インラインスタイルをサニタイズする。