Skip to content

Instantly share code, notes, and snippets.

@phpbits
Created June 2, 2023 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phpbits/327dfeebea7379851937bf591c8e8449 to your computer and use it in GitHub Desktop.
Save phpbits/327dfeebea7379851937bf591c8e8449 to your computer and use it in GitHub Desktop.
Modifying, Editing, and Saving Post Meta Values in the Gutenberg Block Editor: https://jeffreycarandang.com/how-to-enable-read-and-update-post-meta-in-the-wordpress-block-editor-gutenberg/(opens in a new tab)
import { __ } from '@wordpress/i18n';
import { useSelect, useDispatch } from '@wordpress/data';
import { PanelBody, PanelRow, TextControl } from '@wordpress/components';
import { InspectorControls } from '@wordpress/block-editor';
/**
* My Custom Block
*/
const MyCustomBlock = () => {
const META_KEY = 'custom_post_meta';
const { editPost } = useDispatch('core/editor');
const meta = useSelect((select) =>
select('core/editor').getEditedPostAttribute('meta')
);
const { [META_KEY]: customMeta } = meta;
const onCustomMetaChange = (newValue) => {
editPost({
meta: { ...meta, [META_KEY]: newValue },
});
};
return (
<div>
<InspectorControls>
<PanelBody title={__('Settings', 'textdomain')}>
<PanelRow>
<TextControl
label={__('Custom Meta', 'textdomain')}
value={customMeta}
onChange={onCustomMetaChange}
/>
</PanelRow>
</PanelBody>
</InspectorControls>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment