Created
June 2, 2023 09:18
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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