'Wordpress custom meta not updating from a custom Setting Panel in Gutenberg
I am trying to make a custom post setting panel in gutenberg with custom meta to save my options, but the meta is not updating correctly.
I am using a dropdown with custom values and the meta gets saved on the first save, BUT if I change the value of the dropdown again, and click click save, it won't actually update the meta in the database and will show the previous value after I refresh the page.
How to do ? Thanks
Here is my code :
I register my custom meta with php:
function myguten_register_post_meta() {
register_post_meta('post', 'my_custom_meta', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function() {
return current_user_can('edit_posts');
}
]);
}
add_action( 'init', 'myguten_register_post_meta' );
And the JS:
const { registerPlugin } = wp.plugins;
import My_Custom_Panel from './my-custom-panel';
const MyPanel= () => {
return (
<My_Custom_Panel />
);
}
registerPlugin('my-custom-panel', {
render: MyPanel,
icon: 'format-image',
});
my-custom-panel.js:
const { __ } = wp.i18n;
const { useSelect, useDispatch } = wp.data;
const { PluginDocumentSettingPanel } = wp.editPost;
const { PanelRow, SelectControl } = wp.components;
const My_Custom_Panel = () => {
const templateId = useSelect((select) =>
select('core/editor').getEditedPostAttribute('meta')['my_custom_meta']
);
const { editPost } = useDispatch('core/editor');
return (
<PluginDocumentSettingPanel
name="my-panel"
title="My Panel"
className="my-panel"
>
<PanelRow>
<SelectControl
label={__('Select template...', 'txtdomain')}
value={templateId}
onChange={(value) => editPost({ meta: { my_custom_meta: value } })}
options={[
{ label: "tpl 1", value: "t1" },
{ label: "tpl 2", value: "t2" },
{ label: "tpl 3", value: "t3" },
]}
/>
</PanelRow>
</PluginDocumentSettingPanel>
)
};
export default My_Custom_Panel ;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
