【WordPress】はじめてのブロックエディター開発

この記事では、WordPressでブロック開発をした際のメモです。

WordPressで必要最低限のブロックを開発するには、@wordpress/create-blockパッケージを作成することですぐにできます。

参考:チュートリアル: はじめてのブロック作成

create-blockパッケージの作成

新規のブロックエディターの登録は、プラグインの仕組みを利用して、行われます。

作業ディレクトリで以下のコマンドを実行すると、@wordpress/create-blockパッケージが作成されます。

npx @wordpress/create-block@latest myblock 

myblockの部分は、作成されるディレクトリの名称です。

@wordpress/create-blockパッケージは、ブロック作成及び登録に必要なファイル構造のテンプレートを作成してくれる公式パッケージです。

パッケージの実行時には、以下のような表示があります。Ok to proceed? (y)と表示されたら、yを入力しエンターを押します。

Need to install the following packages:
@wordpress/create-block@4.62.0
Ok to proceed? (y) y


Creating a new WordPress plugin in the /Users/xxx/Documents/Development/WordPress/myblock directory.

Creating a "block.json" file.

Creating a "package.json" file.

Installing `@wordpress/scripts` package. It might take a couple of minutes...

Formatting JavaScript files.

Compiling block.

Done: WordPress plugin Myblock bootstrapped in the /Users/xxx/Documents/Development/WordPress/myblock directory.

You can run several commands inside:

  $ npm start
    Starts the build for development.

  $ npm run build
    Builds the code for production.

  $ npm run format
    Formats files.

  $ npm run lint:css
    Lints CSS files.

  $ npm run lint:js
    Lints JavaScript files.

  $ npm run plugin-zip
    Creates a zip file for a WordPress plugin.

  $ npm run packages-update
    Updates WordPress packages to the latest version.

To enter the directory type:

  $ cd myblock

You can start development with:

  $ npm start

Code is Poetry

次のように作業ディレクトリに、指定した名称のファルダが作成されます。

そのフォルダの中には、ブロックの作成に必要なファイルが作成された状態になっています。

wp-envの実行

作成したプラグインディレクトリに移動し、wp-env startを実行します。

cd myblock
wp-env start

実行に成功すれば、次のような表示が出ます。

⚠ Warning: could not find a .wp-env.json configuration file and could not determine if '/Users/xxx/Documents/Development/WordPress/myblock' is a WordPress installation, a plugin, or a theme.
WordPress development site started at http://localhost:8888
WordPress test site started at http://localhost:8889
MySQL is listening on port 61623
MySQL for automated testing is listening on port 61630

 ✔ Done! (in 19s 404ms)

http://localhost:8888/wp-admin/より、ユーザー名:admin、パスワード:passwordで管理画面へログインします。

インストール済みプラグインを開くと、作成したブロックがプラグインとして存在していることがわかります。

ブロックの確認

投稿画面で作成したブロックを確認します。

作成したブロックは、Widgetエリアに存在します。

投稿文に挿入してみると、エディター画面では「Myblock – hello from the editor!」と表示されます。

一方でプレビュー画面では、「Myblock – hello from the saved content!」と表示されます。

公開すると、プレビューと同様の表示に加えて、コンソールで出力が確認できます。

テンプレートで作成されたブロックは、閲覧する状況で表示される内容が変わる仕組みであることがわかります。

エディターに戻り、ブロックの設定項目を確認します。

ブロックの項目は以下のようになっています。

  • 名称:Myblock
  • 説明:xxx

また追加CSSの設定が行えます。

ブロックの基本設定

作成したブロックの基本的な設定項目は、srcフォルダ内にあるblock.jsonに記載されています。

初期状態は以下の内容が記載されています。

{
	"$schema": "https://schemas.wp.org/trunk/block.json",
	"apiVersion": 3,
	"name": "create-block/myblock",
	"version": "0.1.0",
	"title": "Myblock",
	"category": "widgets",
	"icon": "smiley",
	"description": "Example block scaffolded with Create Block tool.",
	"example": {},
	"supports": {
		"html": false
	},
	"textdomain": "myblock",
	"editorScript": "file:./index.js",
	"editorStyle": "file:./index.css",
	"style": "file:./style-index.css",
	"viewScript": "file:./view.js"
}

さきほど確認したブロックの名称と説明はそれぞれ、titledescriptionに対応した内容であることがわかります。

ブロックのタイトル横に表示されていたアイコンは、iconの値がsmileyになっていることから、スマイルマークが表示されているのだと推測できます。

またcategoryの値が、widgetsになっているため、ブロックの挿入でwidgetセクションに表示されていたのだとわかります。

ブロックサポートの追加

WordPressのブロックエディター追加できるブロック用のカスタム機能です。

block.jsonファイル内のsupportsセクションを更新することによって、機能の追加や削除が行えます。

"supports": {
    "color": {
        "background": false,
        "text": true
    },
    "html": false,
    "typography": {
        "fontSize": true
    }
},

変更を加える際に、ターミナルで以下のコマンドを実行しておくと、変更が自動で反映されるようになります。

npm start

npm startを終了するためには、control + Cを入力します。

エディターのブロックの設定項目を確認してみます。次のようにテキストの色とフォントサイズが選択できるようになっています。

ブロックのファイル構成

ブロックエディターを開発するための流れや簡単なカスタマイズを確認しました。

ブロックがどのようなファイル構成からできているか確認をしていきます。

参考:ブロックのファイル構成

  • <plugin-file>.php
  • package.json
  • src フォルダ
  • build フォルダ

<plugin-file>.php

自身でブロックを開発される場合は、基本的にはプラグインとして作成することになります。このファイルにブロック登録用のregister_block_type()関数を記載して、ブロックを登録することになります。

package.json

確認中

srcフォルダ

ブロック開発では、srcフォルダにコンパイルされていない生のコードを格納します。wp-scriptsによって、ビルドが行われて、後で解説するbuildフォルダが出来上がります。

src フォルダのファイル構成は以下になります。

  • block.json
  • index.js
  • edit.js
  • save.js
  • style.(css|scss|sass)
  • editor.(css|scss|sass)
  • render.php
  • view.js

block.json

ブロックのメタデータを含むファイルです。

ビルド後に指すファイルを指定する?

{
	"$schema": "https://schemas.wp.org/trunk/block.json",
	"apiVersion": 3,
	"name": "create-block/myblock",
	"version": "0.1.0",
	"title": "Myblock",
	"category": "widgets",
	"icon": "smiley",
	"description": "Example block scaffolded with Create Block tool.",
	"example": {},
	"supports": {
		"color": {
			"background": false,
			"text": true
		},
		"html": false,
		"typography": {
			"fontSize": true
		}
	},
	"textdomain": "myblock",
	"editorScript": "file:./index.js",
	"editorStyle": "file:./index.css",
	"style": "file:./style-index.css",
	"viewScript": "file:./view.js"
}

index.js

ブロックエディターでロードされるファイルです。ブロックを登録するためのregisterBlockType関数の呼び出し、edit.jsおよびsave.jsのインポートを行います。

/**
 * Registers a new block provided a unique name and an object defining its behavior.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/
 */
import { registerBlockType } from '@wordpress/blocks';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * All files containing `style` keyword are bundled together. The code used
 * gets applied both to the front of your site and to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import './style.scss';

/**
 * Internal dependencies
 */
import Edit from './edit';
import save from './save';
import metadata from './block.json';

/**
 * Every block starts by registering a new block type definition.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/
 */
registerBlockType( metadata.name, {
	/**
	 * @see ./edit.js
	 */
	edit: Edit,

	/**
	 * @see ./save.js
	 */
	save,
} );

edit.js

ブロックエディターで扱うブロックの内容の決定や設定を行います。

/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/
 */
import { __ } from '@wordpress/i18n';

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
 */
import { useBlockProps } from '@wordpress/block-editor';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import './editor.scss';

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
 *
 * @return {Element} Element to render.
 */
export default function Edit() {
	return (
		<p { ...useBlockProps() }>
			{ __( 'Myblock – hello from the editor!', 'myblock' ) }
		</p>
	);
}

save.js

WordPressデータベースに保存される静的なHTMLマークアップを取り決めます。

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
 */
import { useBlockProps } from '@wordpress/block-editor';

/**
 * The save function defines the way in which the different attributes should
 * be combined into the final markup, which is then serialized by the block
 * editor into `post_content`.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save
 *
 * @return {Element} Element to render.
 */
export default function save() {
	return (
		<p { ...useBlockProps.save() }>
			{ 'Myblock – hello from the saved content!' }
		</p>
	);
}

style.(css|scss|sass)

ブロックエディターとフロントエンドの両方に読み込まれるスタイルが含まれます。

/**
 * The following styles get applied both on the front of your site
 * and in the editor.
 *
 * Replace them with your own styles or remove the file completely.
 */

.wp-block-create-block-myblock {
	background-color: #21759b;
	color: #fff;
	padding: 2px;
}

editor.(css|scss|sass)

ブロックエディターのブロックで適用されるスタイルが含まれます。

/**
 * The following styles get applied inside the editor only.
 *
 * Replace them with your own styles or remove the file completely.
 */

.wp-block-create-block-myblock {
	border: 1px dotted #f00;
}

render.php

フロントエンドからのリクエストに対して、データベースに保存された静的なHTMLマークアップをどのように返すか、サーバー側の処理を定義します。静的なHTMLマークアップを動的なHTMLマークアップに変更したい場合に使用されます。

view.js

ブロックが読み込まれる際に、フロントエンドで読み込まれるファイルです。

/**
 * Use this file for JavaScript code that you want to run in the front-end
 * on posts/pages that contain this block.
 *
 * When this file is defined as the value of the `viewScript` property
 * in `block.json` it will be enqueued on the front end of the site.
 *
 * Example:
 *
 * ```js
 * {
 *   "viewScript": "file:./view.js"
 * }
 * ```
 *
 * If you're not making any changes to this file because your project doesn't need any
 * JavaScript running in the front-end, then you should delete this file and remove
 * the `viewScript` property from `block.json`.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#view-script
 */

/* eslint-disable no-console */
console.log( 'Hello World! (from create-block-myblock block)' );
/* eslint-enable no-console */

build フォルダ

srcフォルダのコードをコンパイルした、バージョンが格納されます。

ビルドプロセスによって生成される内容のため、開発時に自身でこのフォルダ内のファイルを変更することは基本的にありません。

block.json

ユーザーの設定の永続化

ユーザーの設定を永続化したい場合に、attributesを用います。

"attributes": {
    "fallbackCurrentYear": {
        "type": "string"
    },
    "showStartingYear": {
        "type": "boolean"
    },
    "startingYear": {
        "type": "string"
    }
},

ブロックのカスタマイズ

ブロックの汎用的なカスタマイズは、supportsを使用します。

"supports": {
    "color": {
        "text": true,
        "link": true,
        "background": true
    }
}
よかったらシェアしてね!
  • URLをコピーしました!