Last Updated: February 7, 2015 | Reading Time: 2 minutes
By using wp_add_metabox you’ll be able add custom field to post, page, or custom post type. But there’s a case; how to add WordPress’ TinyMCE into a custom field?
The main key is by adding wp_editor function.
[php]
wp_editor( $content, $editor_id, $settings = array() );
[/php]
You can read complete description of the function at the codex.
We are going through fast lane how to implement wp_editor. Take a look at the code below:
[php]
/* Init the Meta Box */
function wpop_add_meta_box_portfolio() {
add_meta_box( ‘portfolio_description’, __(‘Description’, ‘wpop-fotofolio’), ‘wpop_metabox_description’, ‘wpop-portfolio’, ‘normal’, ‘default’);
}
add_action(‘add_meta_boxes’, ‘wpop_add_meta_box_portfolio’);
/* Display the Meta Box */
function wpop_metabox_description( $post ) {
wp_nonce_field( ‘wpop_meta_box’, ‘wpop_meta_box_nonce’ );
$photo_description = get_post_meta( $post->ID, ‘wpop_photo_desc’, true );
/* Add WP Editor as replacement of textarea */
wp_editor( $photo_description, ‘wpop_photo_desc’, array(
‘wpautop’ => true,
‘media_buttons’ => false,
‘textarea_name’ => ‘wpop_photo_desc’,
‘textarea_rows’ => 10,
‘teeny’ => true
) );
}
function wpop_save_meta_box_data( $post_id ) {
/* Do the checks */
if ( ! isset( $_POST[‘wpop_meta_box_nonce’] ) ) {
return;
}
if ( ! wp_verify_nonce( $_POST[‘wpop_meta_box_nonce’], ‘wpop_meta_box’ ) ) {
return;
}
if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE ) {
return;
}
// Check the user’s permissions.
if ( isset( $_POST[‘post_type’] ) && ‘page’ == $_POST[‘post_type’] ) {
if ( ! current_user_can( ‘edit_page’, $post_id ) ) {
return;
}
} else {
if ( ! current_user_can( ‘edit_post’, $post_id ) ) {
return;
}
}
/* If check passed then save */
$photo_desc = $_POST[‘wpop_photo_desc’];
update_post_meta( $post_id, ‘wpop_photo_desc’, $photo_desc);
}
add_action( ‘save_post’, ‘wpop_save_meta_box_data’ );
[/php]
Above code is a simple example to display a custom field with TinyMCE editor. You can paste the code into your functions.php to see how it works.