{"id":4211,"date":"2023-11-17T20:06:31","date_gmt":"2023-11-17T19:06:31","guid":{"rendered":"https:\/\/www.knowboard.de\/?p=4211"},"modified":"2023-11-17T20:06:36","modified_gmt":"2023-11-17T19:06:36","slug":"custom-fields-in-gutenberg","status":"publish","type":"post","link":"https:\/\/www.knowboard.de\/custom-fields-in-gutenberg\/","title":{"rendered":"Custom Fields in Gutenberg"},"content":{"rendered":"\n
Gutenberg\/block editor is using javascript and REST API, so to make this custom field editable via block editor, we need to register this field and make it available in WordPress REST API:<\/p>\n\n\n\n
register_post_meta(\n\t'post',\n\t'_my_data',\n\t[\n\t\t'show_in_rest' => true,\n\t\t'single' => true,\n\t\t'type' => 'string',\n\t\t'auth_callback' => function() {\n\t\t\treturn current_user_can( 'edit_posts' );\n\t\t}\n\t]\n);\n<\/code><\/pre>\n\n\n\nSo, we need to create a js script, and create\/register<\/a>\u00a0editor plugin, and create a \u201cmeta box\u201d using \u201cPluginDocumentSettingPanel<\/a>\u201d component.<\/p>\n\n\n\nconst MyDataSettings = () => {\n \n\treturn (\n\t\t<PluginDocumentSettingPanel name=\"my-data\" title=\"My Data\">\n\t\t\t<TextControl value='' onChange='' \/>\n\t\t<\/PluginDocumentSettingPanel>\n\t);\n};\nif (window.pagenow === 'post') {\n\tregisterPlugin('mydata', {\n\t\trender: MyDataSettings,\n\t\ticon: null,\n\t});\n}\n<\/code><\/pre>\n\n\n\nAnd after we add the code above we will see the meta box, but it will do nothing.<\/p>\n\n\n\n
const MyDataSettings = () => {\n\tconst {\n\t\tmeta,\n\t\tmeta: { _my_data },\n\t} = useSelect((select) => ({\n\t\tmeta: select('core\/editor').getEditedPostAttribute('meta') || {},\n\t}));\n \n\tconst { editPost } = useDispatch('core\/editor');\n \n\tconst [myData, setMyData] = useState(_my_data);\n \n\tuseEffect(() => {\n\t\teditPost({\n\t\t\tmeta: {\n\t\t\t\t...meta,\n\t\t\t\t_my_data: myData,\n\t\t\t},\n\t\t});\n\t}, [myData]);\n \n\treturn (\n\t\t<PluginDocumentSettingPanel name=\"my-data\" title=\"My Data\">\n\t\t\t<TextControl value={myData} onChange={setMyData} \/>\n\t\t<\/PluginDocumentSettingPanel>\n\t);\n};<\/code><\/pre>\n\n\n\nI forgot to mention that, we need to enqueue the script. The easiest way is to simply use\u00a0enqueue_block_editor_assets<\/code>\u00a0action hook because this hook will properly enqueue our script to post edit screen.<\/p>\n\n\n\nadd_action( 'enqueue_block_editor_assets', function() {\n\twp_enqueue_script(\n\t\t'my-data',\n\t\ttrailingslashit( plugin_dir_url( __FILE__ ) ) . 'my-data.min.js',\n\t\t[ 'wp-element', 'wp-blocks', 'wp-components', 'wp-editor' ],\n\t\t'0.1.0',\n\t\ttrue\n\t);\n} );<\/code><\/pre>\n\n\n\n