Created
February 25, 2014 21:03
-
-
Save selenastrain/9217688 to your computer and use it in GitHub Desktop.
A meta box example that adds an additional WYSIWYG editor to a custom post type in WordPress.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Meta box example using wp_editor and a custom post type | |
| * The registered post type name is product and we're adding a sample meta box to it | |
| * This is the basic method that I have used before when I needed to add an additional WYSIWYG editor | |
| * | |
| * Reference: | |
| * https://codex.wordpress.org/Function_Reference/wp_editor | |
| * http://codex.wordpress.org/Function_Reference/register_post_type | |
| * http://codex.wordpress.org/Function_Reference/add_meta_box | |
| */ | |
| class NewMetaBox { | |
| function __construct() { | |
| add_action( 'add_meta_boxes', array( $this, 'new_meta_box' ) ); | |
| add_action( 'save_post', array( $this, 'new_meta_save' ) ); | |
| } | |
| /** | |
| * Register the meta box | |
| */ | |
| function new_meta_box() { | |
| add_meta_box( | |
| 'sample_meta_box', | |
| 'Sample Meta Box', | |
| array( $this, 'sample_meta' ), | |
| 'product', // the name of the post type | |
| 'normal', | |
| 'default' | |
| ); | |
| } | |
| /** | |
| * Prints the meta box content | |
| */ | |
| function sample_meta( $post ) { | |
| wp_nonce_field( plugin_basename( __FILE__ ), 'sample_meta_nonce' ); | |
| $meta = get_post_custom( $post->ID ); | |
| $content = $meta['samplecontentfield'][0]; | |
| echo '<p>'; | |
| wp_editor( $content, 'samplecontentfield' ); | |
| // displays the additional WYSIWYG editor | |
| echo '</p>'; | |
| } | |
| /** | |
| * Saves the meta info in a custom field named 'samplecontentfield' that can be used elsewhere | |
| */ | |
| function new_meta_save( $post_id ) { | |
| global $post; | |
| if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) | |
| return $post_id; | |
| if ( !isset( $_POST['sample_meta_nonce'] ) || !wp_verify_nonce( $_POST['sample_meta_nonce'], plugin_basename( __FILE__ ) ) ) | |
| return $post_id; | |
| $post_type = get_post_type_object( $post->post_type ); | |
| if ( !current_user_can( $post_type->cap->edit_post, $post_id ) ) | |
| return $post_id; | |
| if ( isset( $_POST['samplecontentfield'] ) ? update_post_meta( $post_id, 'samplecontentfield', $_POST ) : delete_post_meta( $post_id, 'samplecontentfield', $_POST ) ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment