MENU

【カスタムブロック開発】ポストタイプをドロップダウンとして取得する

import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import './editor.scss';
import { useSelect } from '@wordpress/data';
import { PanelBody, SelectControl } from '@wordpress/components'

export default function Edit() {
	const postTypes = useSelect( (select) => {
		const data = select("core").getEntityRecords("root", "postType", {
			per_page: -1
		});
		return data?.filter(
			(item) =>
				item.visibility.show_in_nav_menes && item.visibility.show_ui
		);
	})
	return (
		<>
			<InspectorControls>
				<PanelBody title="Destination">
					<SelectControl 
						label="Type" 
						value={props.attributes.postType}
						onChange={(newValue) => {
							props.setAttributes({
								postType: newValue
							})
						}}
						options={[{
							label: "Select a post type...",
							value: ""
							}, ...(postTypes || []).map(postType => (
							{
								label: postType.label.singular_name,
								value: postType.slug
							}
					))]} />
				</PanelBody>
			</InspectorControls>
			<p { ...useBlockProps() }>
				{ __(
					'My Template Block – hello from the editor!',
					'my-template-block'
				) }
			</p>
		</>
	);
}