<?php
/**
 * Add and render Metabox for post
 */

add_action( 'add_meta_boxes', 'wpdev_add_post_metabox' );

function wpdev_add_post_metabox() {
	// Add new meta box.
	add_meta_box(
		'wpdev_post_metabox',
		'Test WPeditor',
		'wpdev_render_post_metabox',
		'post',
		'normal'
	);
}

function wpdev_render_post_metabox() {
	global $post;

	// Get saved meta data.
	$post_note_meta_content = get_post_meta( $post->ID, 'wpdev_post_field_tinymce', true );

	// Nonce field.
	wp_nonce_field( 'wpdev_post_metabox_nonce_' . $post->ID, 'wpdev_post_metabox_nonce' );

	// Render editor metabox.
	wp_editor(
		$post_note_meta_content,
		'wpdev_post_field_tinymce',
		array( 'textarea_rows' => '5' )
	);
}

/**
 * Save post metabox
 */

add_action( 'save_post', 'wpdev_save_post' );

function wpdev_save_post( $post_id ) {

	// Bail if auto save.
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	// Bail if nonce is missing or nonce verification fails.
	if ( ! isset( $_POST['wpdev_post_metabox_nonce'] ) || ! wp_verify_nonce( $_POST['wpdev_post_metabox_nonce'], 'wpdev_post_metabox_nonce_' . $post_id ) ) {
		return;
	}

	// Bail is current user is allowed to edit posts.
	if ( ! current_user_can( 'edit_post' ) ) {
		return;
	}

	// Make sure our data is set before trying to save it.
	if ( isset( $_POST['wpdev_post_field_tinymce'] ) ) {
		update_post_meta( $post_id, 'wpdev_post_field_tinymce', $_POST['wpdev_post_field_tinymce'] );
	}
}