Skip to content

Instantly share code, notes, and snippets.

@vralle
Created January 7, 2022 22:25
Show Gist options
  • Save vralle/371720794af0d519ce5a4e0dfc06b906 to your computer and use it in GitHub Desktop.
Save vralle/371720794af0d519ce5a4e0dfc06b906 to your computer and use it in GitHub Desktop.
Use post meta in gutenberg
// https://make.wordpress.org/core/2020/03/02/general-block-editor-api-updates/
// https://github.com/WordPress/gutenberg/tree/trunk/packages/core-data
import {
PanelRow, TextControl,
} from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useEntityProp } from '@wordpress/core-data';
import { PluginDocumentSettingPanel } from '@wordpress/edit-post';
import { registerPlugin } from '@wordpress/plugins';
function CustomMetaPanel() {
const postType = useSelect(
(select) => select('core/editor').getCurrentPostType(),
[],
);
const [meta, setMeta] = useEntityProp('postType', postType, 'meta');
const metaValue = meta.customMeta;
const updateMetaValue = (newValue) => {
setMeta({ ...meta, customMeta: newValue });
};
return (
<PluginDocumentSettingPanel name="customMetaPanel" title="Custom meta">
<PanelRow>
<TextControl
label="Custom meta"
value={metaValue}
onChange={updateMetaValue}
className="custom-meta-field"
/>
</PanelRow>
</PluginDocumentSettingPanel>
);
}
registerPlugin('plugin-name', {
render: CustomMetaPanel,
icon: '',
});
@clifgriffin
Copy link

Thanks for this - was struggling to get this working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment