1

I can't figure out how to save the changed attribute value to post meta, could somebody help?

I've registered the attribute altogether with my block:

register_meta('post', 'showUntil', array(
    'show_in_rest' => true,
    'auth_callback' => function () {
        return current_user_can('edit_posts');
    },
    'sanitize_callback' => 'sanitize_text_field',
    'show_in_rest'      => true,
    'single'            => true,
    'type'              => 'string',
));

I have the following attributes:

atrributes: {
    showUntil: {
        type: 'string',
        source: 'meta',
        meta: 'showUntil'
    },
}

I can update the value with setAttribute etc., but how to actually save the post meta?

Thanks a lot!

4

1 Answer 1

1

Here's how to read and save custom post meta in the Gutenberg block editor.

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 = 'showUntil'; // This is your custom meta name
    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>
    );
};

You could also check this complete tutorial of mine on how to create and manage the custom post meta on the Gutenberg block editor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.