メインコンテンツへスキップ
見出し画像

WordPressで気軽にカスタムブロックを追加したい

    こんにちは!株式会社デパートのエンジニアの熊谷です。
    GWは水族館のラッコの動画に癒されておりました🦦

    みなさんはWordPressでブロックエディタをカスタマイズする際、ボタンやテーブル、リストタグなどで、「単純にクラスを付けたいだけ」や「特定の属性をセットした状態で呼び出したい」といったケースはありませんか?

    そのためだけにカスタムブロックをJSXやReact駆使して作成するのは骨が折れると思われるのですが、そのお悩みは管理画面でグローバル登録されているwp標準の関数、wp.blocks.registerBlockVariationを利用して既存のブロックを拡張することで解消することができます!

    画像

    Block Variation(バリエーション)を使うメリット

    ブロックバリエーションを使うと、インサーター(ブロック追加画面)に独立したブロックとして表示されます。

    最初から特定のクラスや属性(テーブルのヘッダー設定など)が適用された状態で挿入でき、ユーザに複雑な入力を求めること無く、別デザインのブロックを挿入してもらうことができます。

    画像

    基本的な登録方法

    管理画面では wp オブジェクトがグローバルに登録されています。wp.domReady 内で実行するのが基本です。

    // assets/js/editor.js
    
    wp.domReady(function () {
        // ここに登録処理を記述
    });
    

    実装例1:数字リスト

    リストブロックに特定のスタイル(クラス)を付与し、さらに初期値として2つのリストアイテムが入った状態で登録します。

      // 数字リスト
    wp.blocks.registerBlockVariation('core/list', {
        name: 'num-circle-dashed-list',
        title: '数字リスト',
        icon: 'editor-ol',
        attributes: {
    		className: 'is-style-num_circle',
    		ordered: true, // あらかじめ数字リスト(olタグ)に設定
        },
        isDefault: false,
        example: {
    		attributes: {
    			className: 'is-style-num_circle',
    			ordered: true, // あらかじめ数字リスト(olタグ)に設定
    		},
    		innerBlocks: [
    			{ name: 'core/list-item',  attributes: { content: '項目 1' } },
    			{ name: 'core/list-item',  attributes: { content: '項目 2' } },
    		],
        },
    });
    

    実装例2:2列テーブル(左見出し)

    最初から「ヘッダー」属性がセットされ、セルのタグが th になっている2列のテーブルです。

    // 2列テーブル(左見出し)
    wp.blocks.registerBlockVariation('core/table', {
        name: 'table-th-left',
        title: '2列テーブル(左見出し)',
        icon: 'layout',
        attributes: {
    		className: 'alignleft is-all-centered--va',
    		body: [
    		{
    			cells: [
    				{ content: '項目', tag: 'th' },
    				{ content: '内容', tag: 'td' },
    			],
    		},
    		{
    			cells: [
    				{ content: '項目', tag: 'th' },
    				{ content: '内容', tag: 'td' },
    			],
    		},
    		],
        }
    });
    

    実装例3:お問い合わせボタン

    特定のクラスと配色、さらにアイコンをセットにしたボタンです。
    textプロパティでデフォルトのテキストを指定することもできます。

    wp.blocks.registerBlockVariation('core/button', {
        name: 'contact-button',
        title: 'お問い合わせボタン',
        description: 'メールアイコン付きの問い合わせ用ボタンです',
        icon: 'email-alt', // Dashiconsを指定可能
        attributes: {
            className: 'is-style-arrow',
            text: '<svg class="c-btn-icon c-btn-icon-mail" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M3 6h18v12H3V6Zm1.7 1.5 7.3 5.9 7.3-5.9" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg><span class="c-btn-label">お問い合わせはこちら</span>',
            backgroundColor: 'vivid-red',
        },
    });
    

    一歩進んだテクニック

    isActive でバリエーションを認識させる

    バリエーションを登録しただけだと、エディタ上で選択した際に「標準のブロック」として認識されてしまうことがあります。isActive を設定すると、どのバリエーションを選択中かを正しく判別できるようになります。

    wp.blocks.registerBlockVariation('core/list', {
        name: 'checked-list',
        title: 'チェックリスト',
        attributes: { className: 'is-style-checked' },
        isActive: (blockAttributes, variationAttributes) =>
            blockAttributes.className === variationAttributes.className,
    });
    

    keywords と scope

    • keywords: インサーターの検索で見つけやすくします。

    • scope: ['inserter'] を指定すると、ブロック追加画面にのみ表示され、ブロック変換などには表示されなくなります。

    // 数字リスト
    wp.blocks.registerBlockVariation('core/list', {
      name: 'num-circle-dashed-list',
      title: '数字リスト',
      icon: 'editor-ol',
      scope: [ 'inserter', 'block' ], // inserterとblock変換に表示されます
      keywords: [ '数字', '番号', 'リスト' ], // ブロック検索用キーワード
      attributes: {
        className: 'is-style-num_circle',
        ordered: true,
      },
    });

    ブロックエディタ側へのスタイル適用

    JSでクラスを付与しても、エディタ上で見た目が反映されていないと編集しづらいため、エディタ専用のスタイルを適用します。

    方法1:enqueue_block_editor_assets で読み込む

    JSと一緒にエディタ専用CSSを読み込ませる方法です。

    // functions.php
    
    function my_enqueue_block_editor_assets() {
        // エディタ用JS
        wp_enqueue_script(
            'my-block-editor-script',
            get_template_directory_uri() . '/assets/js/editor.js',
            array( 'wp-blocks', 'wp-dom-ready', 'wp-edit-post' ),
            filemtime( get_template_directory() . '/assets/js/editor.js' ),
            true
        );
    
        // エディタ用CSS
        wp_enqueue_style(
            'my-block-editor-style',
            get_template_directory_uri() . '/assets/css/editor-style.css',
            array(),
            filemtime( get_template_directory() . '/assets/css/editor-style.css' )
        );
    }
    add_action( 'enqueue_block_editor_assets', 'my_enqueue_block_editor_assets' );
    

    方法2:add_editor_style を使う(推奨)

    add_editor_style を使うと、WordPressが自動的にセレクタをラップしてくれるため、フロント用のCSSをそのままエディタに流用しやすくなります。

    // functions.php
    
    function my_setup_theme() {
        // エディタスタイルのサポートを有効化
        add_theme_support( 'editor-styles' );
    
        // フロント共通、またはエディタ用のCSSを指定
        add_editor_style( 'assets/css/editor-style.css' );
    }
    add_action( 'after_setup_theme', 'my_setup_theme' );
    

    まとめ

    registerBlockVariation を使うことで、エンジニアはメンテナンスコストを抑えられ、ユーザ(編集者)は迷わずに決まったデザインのブロックを呼び出すことができます。

    「わざわざカスタムブロックを作るほどではないけど、標準のままだと使いにくい」、「標準ブロックのデザインバリエーションを増やしたい」という要望を叶えるには最適な手法です。

    WordPressでオウンドメディアなどを運用する場合、差別化を図るためデザインをユニークにするケースはよくあると思われます。
    長いことWordPressを触ってきましたが、今回初めてregisterBlockVariation()やadd_editor_style()について知ることができました。

    みなさんもよいWordPressライフを!

     
     
    株式会社デパートでフロントエンドエンジニアやってます!まいど!

    あなたへのおすすめ