Note
Warning
既存のテーマを編集する場合、各種ブロックはコンパイル済みのものがアセットフォルダにある場合あり。
wp-content/plugins
に遷移し以下のコマンドで雛形を生成する
npx @wordpress/create-block block-name
生成されるファイルは以下の通り。
関連のパッケージと各種Scaffoldのファイルが生成される。基本的にいじるのはsrc
内の各種アセット系と.php
ファイルになりそう。
.
├── build
├── node_modules
├── block-name.php
├── package.json
├── package-lock.json
├── readme.txt
└── src
生成されたディレクトリに移動し以下のコマンドを実行する。 こちらでローカル開発環境で確認できるようになるらしい。
npm run start
以下を実行することで本番環境に反映される。
npm run build
実装
block.json
というファイルが設定のファイルになり、こちらにブロックに設定する変数などの記述を行う。
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "instagram/instagram-post",
"parent": [ "instagram/instagram-post-list" ],
"version": "0.1.0",
"title": "Instagram Post",
"category": "widgets",
"icon": "smiley",
"description": "Example block scaffolded with Create Block tool.",
"example": {},
"supports": {
"html": false
},
"attributes": {
"url": {
"type": "string",
"source": "attribute",
"selector": "a",
"attribute": "href"
},
"imageUrl": {
"type": "string"
},
"imageAlt": {
"type": "string"
}
},
"textdomain": "instagram",
"editorScript": "file:./index.js",
"editorStyle": "file:./index.css",
"style": "file:./style-index.css",
"viewScript": "file:./view.js"
}
基本的にはJSX
で記述を行い、公式のパッケージから提供されるhooksを用いて編集画面、実際の表示画面の実装を進める。
index.js
がルートのファイルになるためそちらを編集する。
edit
が編集画面、save
が実際に表示される画面に該当するのでそれぞれ適切にDOMを返すように実装。
Scaffoldで生成した場合、EditとSaveはそれぞれ別ファイルに分けて実装されている。
registerBlockType(metadata.name, {
/**
* @see ./edit.js
*/
edit: ({ attributes, setAttributes }) => {
const { url, imageUrl } = attributes;
const blockProps = useBlockProps();
return (
<>
<InspectorControls>
<PanelBody title={__("Settings", "instagram-block")}>
<TextControl
label={__("Post link", "instagram-block")}
value={url || ""}
onChange={(value) => setAttributes({ url: value })}
/>
<MediaPlaceholder
onSelect={(media) => {
setAttributes({ imageAlt: media.alt, imageUrl: media.url });
}}
allowedTypes={["image"]}
multiple={false}
labels={{ title: "Upload" }}
/>
</PanelBody>
</InspectorControls>
<div {...blockProps}>
<a class="w-full">
<img
src={imageUrl ? imageUrl : "https://via.placeholder.com/300"}
className="w-full"
/>
</a>
</div>
</>
);
},
/**
* @see ./save.js
*/
save: ({ attributes }) => {
const { imageUrl, imageAlt, url } = attributes;
return (
<a href={url} class="w-full">
<img
src={imageUrl ? imageUrl : "https://via.placeholder.com/500"}
alt={imageAlt}
class="w-full"
/>
</a>
);
},
});
Tips
基本的には
block.json
に設定したattributesを呼び出して表示をする。 editorの場合はsetAttributes
のhookを利用して入力された値を保存する実装が必要。
Tips
その他
@wordpress/block-editor
や@wordpress/components
からさまざまなコンポーネント、フックを利用できるので公式ドキュメントを参考に実装する。
参考
ブロックエディターハンドブック – Japanese Team – WordPress.org 日本語 属性 – Japanese Team – WordPress.org 日本語 edit と save – Japanese Team – WordPress.org 日本語