WordPressブロック開発 任意のaria-labelを設定できるカスタムブロック

段落ブロック利用時に設定パネルから任意のaria-labelを設定できるブロックを作ってみます。アクセシビリティを考慮できていませんが練習用です。

ブロック開発

block.json

段落ブロックの入力テキストを受け取るcontent属性と、aria-labelを格納するariaLabel属性を定義する

"attributes": {
	"content": {
		"type": "string",
		"default": ""
	},
	"ariaLabel": {
		"type": "string",
		"default": ""
	}
},

edit.js

import {
	useBlockProps,
	RichText,
	InspectorControls,
} from "@wordpress/block-editor";

import { PanelBody, TextControl } from "@wordpress/components";

import "./editor.scss";

export default function Edit({ attributes, setAttributes }) {
	const { content, ariaLabel } = attributes;

	return (
		<>
			<InspectorControls>
				<PanelBody title="アクセシビリティ設定" initialOpen={true}>
					<TextControl
						label="ARIA ラベル"
						value={ariaLabel}
						onChange={(value) => {
							setAttributes({ ariaLabel: value });
						}}
						help="スクリーンリーダー向けの説明文です"
					/>
				</PanelBody>
			</InspectorControls>

			<RichText
				{...useBlockProps({ "aria-label": ariaLabel })}
				tagName="p"
				value={content}
				onChange={(newContent) => {
					setAttributes({ content: newContent });
				}}
				placeholder="テキストを入力"
			/>
			<p>{ariaLabel}</p>
		</>
	);
}

完成形

render.php

<?php
$attributes = wp_parse_args($attributes, [
	'content'	=> '',
	'ariaLabel' => ''
]);

$wrapper_attributes = get_block_wrapper_attributes(
	$attributes['ariaLabel'] ? ['aria-label' => esc_attr($attributes['ariaLabel'])] : []
);
?>

<p <?php echo $wrapper_attributes ?>>
	<?php echo wp_kses_post($attributes['content']); ?>
</p>

wp_parse_args関数を使用する理由

  • $attributescontentariaLabel未定義だった場合に、それぞれ空文字をセットする
  • 後続の処理で isset() チェックが不要になる

wp_parse_args( $args, $defaults );

配列のマージとデフォルト値の設定を行う関数

  • $args: 実際に与えられた引数(連想配列、オブジェクト、クエリ文字列もOK)
  • $defaults: デフォルト値を指定した連想配列
  • $args にキーが存在しない場合、$defaults からそのキーと値を補います。
$args = ['tokyo' => 'japan'];
$defaults = ['tokyo' => ''];

$parsed = wp_parse_args($args, $defaults);

// 結果:第二引数が第一引数に上書きされる
Array
(
    [tokyo] => japan
)
$args = ['tokyo' => 'japan'];
$defaults = ['tokyo' => '', 'paris' => 'france'];

$parsed = wp_parse_args($args, $defaults);

// 結果:
Array
(
    [tokyo] => japan
    [paris] => france
)

get_block_wrapper_attributes( array $extra_attributes = [] ): string

ブロックの親要素に付けるべき クラス・データ属性などのHTML属性をまとめて生成する

追加の属性も引数に渡せる

<p <?php echo get_block_wrapper_attributes( [ 'aria-label' => '注目のセクション' ] ); ?>>

// 結果
<p class="wp-block-my-plugin-my-block" aria-label="注目のセクション">