Loading custom post meta in the WordPress Block Editor - markhowellsmead/helpers GitHub Wiki

Loading custom meta for display in the Block Editor.

Reference: https://developer.wordpress.org/news/2023/03/03/creating-a-custom-block-that-stores-post-meta/

In this example, we're loading and displaying the authors custom meta value as a comma-separated list in the edit component of a custom block.

JavaScript

import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps } from '@wordpress/block-editor';
import { Disabled } from '@wordpress/components';
import { useEntityProp } from '@wordpress/core-data';
import { _x } from '@wordpress/i18n';
import { postAuthor as icon } from '@wordpress/icons';

import block_json from '../../../../block.json';
const { name: block_name } = block_json;

registerBlockType(block_name, {
    icon,
    edit: ({ context: { postType, postId } }) => {
        const [meta] = useEntityProp('postType', postType, 'meta', postId);

        const blockProps = useBlockProps();

        const { authors } = meta;

        return (
            <div {...blockProps}>
                <Disabled>
                    {!!authors && authors.length > 0 && (
                        <div>
                            {authors.map((author, index) => (
                                <>
                                    <a key={author.id} href={author.url}>
                                        {author.display_name}
                                    </a>
                                    {index < authors.length - 1 && ', '}
                                </>
                            ))}
                        </div>
                    )}
                    {(!authors || authors.length < 1) && (
                        <div>{_x('No authors found', 'Block editor message', 'sha')}</div>
                    )}
                </Disabled>
            </div>
        );
    },
});

PHP

Make sure that the custom meta is available in the REST API endpoint. Because we're returning custom data for the users in question, we define the specific fields (like display_name or url) using a custom method getAuthors (which isn't shown here).

(Use the method which runs this code on the rest_api_init hook.)

register_rest_field(
	'sht_proarticle',
	'meta',
	[
		'get_callback' => function ($post, $field_name, $request) {
			$custom_meta = array(
				'authors' => $this->getAuthors($post['id'], 'data'),
			);
			$extended_meta = array_merge($post['meta'], $custom_meta);

			return $extended_meta;
		},
		'schema' => null,
	]
);
⚠️ **GitHub.com Fallback** ⚠️