【WordPressブロック開発】動的に表示する段落ブロックを作成する

フロントエンドをrender.phpで表示させる動的なカスタムブロックを作成します。

block.json

attributesを定義

{
	"attributes": {
		"message": {
			"type": "string"
		}
	},
}

edit.js

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

import "./editor.scss";

export default function Edit({ attributes, setAttributes }) {
	const { message } = attributes;
	return (
		<RichText
			{...useBlockProps()}
			tagName="p"
			value={message}
			onChange={(value) => {
				setAttributes({ message: value });
			}}
		/>
	);
}

render.php

<?php
$post_message = isset($attributes['message']) ? $attributes['message'] : "";
?>

<p <?php echo get_block_wrapper_attributes(); ?>>
	<!-- wp_kses_post:<a>や<br>などの投稿本文で許される標準のタグだけを許可する -->
	<?php echo wp_kses_post($post_message); ?>
</p>