Rehan Lodhi
Rehan Lodhi

Reputation: 31

How can I add and save my own custom field in the WordPress Gutenberg (block editor) panel?

gutenberg default pane

I am building a portfolio and need to add a gallery field, didn't found a way to add custom field there in the screenshot, anyone know how it will be done?

Upvotes: 1

Views: 1397

Answers (1)

Rice_Crisp
Rice_Crisp

Reputation: 1261

First register the meta field (php):

register_meta('post', '_my_meta_field', [
    'show_in_rest' => true,
    'single' => true,
    'type' => 'string',
    'auth_callback' => function() {
        return current_user_can('edit_posts');
    }
]);
add_action('init', 'register_meta');

Then make the panel/field (js):

const { TextControl } = wp.components
const { useDispatch, useSelect } = wp.data
const { PluginDocumentSettingPanel } = wp.editPost
const { registerPlugin } = wp.plugins

const PluginDocumentSettingPanelDemo = () => {
    const { meta } = useSelect(select => ({
        meta: select('core/editor').getEditedPostAttribute('meta')
    }))
    const { editPost } = useDispatch('core/editor')
    const setMeta = keyAndValue => {
        editPost({ meta: keyAndValue })
    }
    return (
        <PluginDocumentSettingPanel
            name="custom-panel"
            title="Custom Panel"
            className="custom-panel"
        >
            <TextControl
                onChange={ newValue => setMeta({ '_my_meta_field': newValue }) }
                value={ meta['_my_meta_field'] }
            />
        </PluginDocumentSettingPanel>
    )
}
registerPlugin('plugin-document-setting-panel-demo', {
    render: PluginDocumentSettingPanelDemo
})

Wasn't able to test, so let me know if you get any errors.

Upvotes: 1

Related Questions