Created
June 13, 2011 11:44
-
-
Save acarabott/1022650 to your computer and use it in GitHub Desktop.
Wordpress custom metabox with TinyMCE saving formatting properly
This file contains 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
add_action( 'add_meta_boxes', 'add_metaname_box'); | |
add_action( 'save_post', 'metaname_save'); | |
function add_metaname_box() { | |
add_meta_box( | |
'metaname_id', | |
__( 'Shows text', 'metaname_textdomain'), | |
'metaname_custom_box', | |
'page' | |
); | |
} | |
function metaname_custom_box() { | |
global $post; | |
wp_nonce_field( plugin_basename( __FILE__ ), 'metaname_noncename' ); | |
$data = get_post_meta($post->ID, 'metaname_custom_box', true); | |
echo <<<EOT | |
<script type="text/javascript"> | |
jQuery(document).ready(function() { | |
jQuery("#metaname_custom_box").addClass("mceEditor"); | |
if ( typeof( tinyMCE ) == "object" && | |
typeof( tinyMCE.execCommand ) == "function" ) { | |
tinyMCE.execCommand("mceAddControl", false, "metaname_custom_box"); | |
} | |
}); | |
</script> | |
<textarea id="metaname_custom_box" name="metaname_custom_box">$data</textarea> | |
EOT; | |
} | |
function metaname_save($post_id) { | |
global $post; | |
// Verify | |
if ( !wp_verify_nonce( $_POST['metaname_noncename'], plugin_basename(__FILE__) )) { | |
return $post_id; | |
} | |
if ( 'page' == $_POST['post_type'] ) { | |
if ( !current_user_can( 'edit_page', $post_id )) | |
return $post_id; | |
} else { | |
if ( !current_user_can( 'edit_post', $post_id )) | |
return $post_id; | |
} | |
$key = 'metaname_custom_box'; | |
$data = wpautop($_POST[$key]); | |
// New, Update, and Delete | |
if(get_post_meta($post_id, $key) == "") | |
add_post_meta($post_id, $key, $data, true); | |
elseif($data != get_post_meta($post_id, $key, true)) | |
update_post_meta($post_id, $key, $data); | |
elseif($data == "") | |
delete_post_meta($post_id, $key, get_post_meta($post_id, $key, true)); | |
} |
Glad it helped
Great!
Is it possible to add "Visual" and "Text" to this like the wp_editor?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thx for this