Series: Gutenberg Tutorials

Custom Field & Meta Box in Gutenberg Editor

How to do this in the “new” way?

From this:

To this:

Creating a custom field using a custom meta box is simple and very straightforward.

Basically we create a meta box using meta box API and add it in post meta data using save_post hook.

Here’s the basic code:

// Add field:
add_action( 'add_meta_boxes', function() {
	add_meta_box(
		'my_meta_box',
		'My Meta Box',
		function( $post ) {
			wp_nonce_field( __FILE__, '_my_data_nonce' );
			?>
			<p><input type="text" class="large-text" name="my_data" value="<?php echo esc_attr( get_post_meta( $post->ID, '_my_data', true ) ); ?>"></p>
			<?php
		},
		'post',
		'side'
	);
} );
// Save field.
add_action( 'save_post', function( $post_id ) {
	if ( isset( $_POST['my_data'], $_POST['_my_data_nonce'] ) && wp_verify_nonce( $_POST['_my_data_nonce'], __FILE__ ) ) {
		update_post_meta( $post_id, '_my_data', sanitize_text_field( $_POST['my_data'] ) );
	}
} );

But how to do this in the new way?

Read More Custom Field & Meta Box in Gutenberg Editor