Skip to content

Custom Fields in Gutenberg

Gutenberg/block editor is using javascript and REST API, so to make this custom field editable via block editor, we need to register this field and make it available in WordPress REST API:

register_post_meta(
	'post',
	'_my_data',
	[
		'show_in_rest' => true,
		'single'       => true,
		'type'         => 'string',
		'auth_callback' => function() {
			return current_user_can( 'edit_posts' );
		}
	]
);

So, we need to create a js script, and create/register editor plugin, and create a “meta box” using “PluginDocumentSettingPanel” component.

const MyDataSettings = () => {
 
	return (
		<PluginDocumentSettingPanel name="my-data" title="My Data">
			<TextControl value='' onChange='' />
		</PluginDocumentSettingPanel>
	);
};
if (window.pagenow === 'post') {
	registerPlugin('mydata', {
		render: MyDataSettings,
		icon: null,
	});
}

And after we add the code above we will see the meta box, but it will do nothing.

const MyDataSettings = () => {
	const {
		meta,
		meta: { _my_data },
	} = useSelect((select) => ({
		meta: select('core/editor').getEditedPostAttribute('meta') || {},
	}));
 
	const { editPost } = useDispatch('core/editor');
 
	const [myData, setMyData] = useState(_my_data);
 
	useEffect(() => {
		editPost({
			meta: {
				...meta,
				_my_data: myData,
			},
		});
	}, [myData]);
 
	return (
		<PluginDocumentSettingPanel name="my-data" title="My Data">
			<TextControl value={myData} onChange={setMyData} />
		</PluginDocumentSettingPanel>
	);
};

I forgot to mention that, we need to enqueue the script. The easiest way is to simply use enqueue_block_editor_assets action hook because this hook will properly enqueue our script to post edit screen.

add_action( 'enqueue_block_editor_assets', function() {
	wp_enqueue_script(
		'my-data',
		trailingslashit( plugin_dir_url( __FILE__ ) ) . 'my-data.min.js',
		[ 'wp-element', 'wp-blocks', 'wp-components', 'wp-editor' ],
		'0.1.0',
		true
	);
} );
https://github.com/turtlepod/my-data

Dieser Beitrag hat 0 Kommentare

Schreibe einen Kommentar

Deine E-Mail wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

An den Anfang scrollen