Skip to content

Instantly share code, notes, and snippets.

@Arifursdev
Last active January 25, 2025 15:56
Show Gist options
  • Save Arifursdev/016731dd01706c4d477281200ad5c330 to your computer and use it in GitHub Desktop.
Save Arifursdev/016731dd01706c4d477281200ad5c330 to your computer and use it in GitHub Desktop.
Add Metafields on WP BlockEditor
(function (wp) {
    
    const el = wp.element.createElement;

    if (!wp.plugins) {
        return;
    }
    
    const { registerPlugin } = wp.plugins;
    const { PluginDocumentSettingPanel } = wp.editPost;

    const { TextControl } = wp.components;
    const { withSelect } = wp.data;
    const { withDispatch } = wp.data;
    const { compose } = wp.compose;

    // 
    let BlockEditorFields = (props) => {
        return el(
            PluginDocumentSettingPanel,
            {
                title: 'New Settings',
            },
            el(TextControl, {
                label: 'My Field',
                value: props.customTitle,
                onChange: (value) => {
                    props.setCustomTitle(value);
                },
            }),
            el(TextControl, {
                label: 'My Content',
                value: props.customContent,
                onChange: (value) => {
                    props.setCustomContent(value);
                },
            })
        );
    };

    BlockEditorFields = compose([
        withSelect((select) => {
            return {
                customTitle: select('core/editor').getEditedPostAttribute('meta')['customTitle'],
                customContent: select('core/editor').getEditedPostAttribute('meta')['customContent'],
            };
        }),
        withDispatch((dispatch) => {
            return {
                setCustomTitle: (value) => {
                    dispatch('core/editor').editPost({ meta: { customTitle: value } });
                },
                setCustomContent: (value) => {
                    dispatch('core/editor').editPost({ meta: { customContent: value } });
                },
            };
        }),
    ])(BlockEditorFields);
    
    registerPlugin('document-setting-test', { render: BlockEditorFields });

})(window.wp);
... 

add_action( 'init', 'abcd_post_metas' );
function abcd_post_metas() {
    register_post_meta( 'post', 'customTitle', [
        'show_in_rest' => true,
        'single' => true,
        'type' => 'string',
    ] );

    register_post_meta( 'post', 'customContent', [
        'show_in_rest' => true,
        'single' => true,
        'type' => 'string',
    ] );
}


add_action( 'admin_enqueue_scripts', 'abcd_assets' );
function assets() {
    wp_enqueue_script( 'script-handle' ); // after registering the script, dependencies: 'jquery', 'wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n', 'wp-data', 'wp-block-editor'
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment