WordPressのCSS・JS読み込みとGutenbergやブロックテーマの対応方法

WordPressテーマ開発において、CSSやJavaScriptの適切な読み込みは重要な要素です。この記事では、特にブロックテーマ(Block Theme)におけるスクリプト・スタイルの読み込み方法と、Gutenberg(ブロックエディター)対応の方法について詳しく解説します。

基本:CSS・JSの読み込み(キャッシュ対策付き)

以下のコードは、テーマの functions.php に記述して使用します。更新日時をバージョンとして指定し、キャッシュを無効化するテクニックを使っています。

function mytheme_enqueue_assets() {
    $theme_path = get_stylesheet_directory();
    $theme_uri  = get_stylesheet_directory_uri();

    // フロント用CSS
    $style_path = $theme_path . '/style.css';
    if (file_exists($style_path)) {
        wp_enqueue_style(
            'mytheme-style',
            $theme_uri . '/style.css',
            array(),
            filemtime($style_path)
        );
    }

    // フロント用JS(jQuery依存あり)
    $script_path = $theme_path . '/main.js';
    if (file_exists($script_path)) {
        wp_enqueue_script(
            'mytheme-main',
            $theme_uri . '/main.js',
            array('jquery'),
            filemtime($script_path),
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'mytheme_enqueue_assets');
PHP

Gutenberg(ブロックエディター)用のCSS・JS読み込み

ブロックエディターにも専用のCSSやJSを読み込むことが可能です。

function mytheme_enqueue_block_editor_assets() {
    $theme_path = get_stylesheet_directory();
    $theme_uri  = get_stylesheet_directory_uri();

    // エディター用CSS
    $editor_style = $theme_path . '/editor-style.css';
    if (file_exists($editor_style)) {
        wp_enqueue_style(
            'mytheme-editor-style',
            $theme_uri . '/editor-style.css',
            array(),
            filemtime($editor_style)
        );
    }

    // エディター用JS
    $editor_js = $theme_path . '/editor.js';
    if (file_exists($editor_js)) {
        wp_enqueue_script(
            'mytheme-editor-script',
            $theme_uri . '/editor.js',
            array('wp-blocks', 'wp-dom-ready', 'wp-edit-post'),
            filemtime($editor_js),
            true
        );
    }
}
add_action('enqueue_block_editor_assets', 'mytheme_enqueue_block_editor_assets');
PHP

theme.json の活用

ブロックテーマでは、theme.json によって色・タイポグラフィ・レイアウトなどを制御します。

例:theme.json

{
  "version": 2,
  "settings": {
    "color": {
      "palette": [
        {
          "slug": "primary",
          "color": "#0073aa",
          "name": "Primary"
        }
      ]
    },
    "typography": {
      "fontSizes": [
        {
          "slug": "large",
          "size": "2rem",
          "name": "Large"
        }
      ]
    }
  },
  "styles": {
    "elements": {
      "h1": {
        "typography": {
          "fontSize": "2.5rem"
        }
      }
    }
  }
}
JSON

Gutenbergブロック制御(例:特定ブロックを無効化)

ブロックエディター用の editor.js に以下のようなコードを記述すれば、特定のブロックを無効化することも可能です。

// editor.js
wp.domReady(() => {
  wp.blocks.unregisterBlockType('core/cover');
});
JavaScript

推奨ディレクトリ構成

your-theme/
├─ style.css
├─ theme.json
├─ functions.php
├─ main.js
├─ editor-style.css
├─ editor.js
└─ templates/
JavaScript

まとめ

ブロックテーマを使ったモダンなWordPressテーマ開発には、theme.jsonとエディター対応が不可欠です。本記事の方法をベースに、自分だけの高機能なブロックテーマを構築してみてください!

read next