All I really want is for the meta box data to be saved A) as an accessible global variable inside the loop and B) to save the data to the textbox so that when the user presses update what they have written appears in the textbox until it is updated again. Currently, i know it doesn’t fit the criteria for B), and I’m not sure whether or not it is accessible as a global variable in the loop. Any help?
add_action( 'add_meta_boxes', 'testimonial_text_box' );
function testimonial_text_box() {
add_meta_box(
'testimonial_text_box',
__( 'Testimonial Text:', 'myplugin_textdomain' ),
'testimonial_text_box_content',
'testimonial',
'normal',
'high'
);
}
function testimonial_text_box_content( $post ) {
$values = get_post_custom( $post->ID );
$text = isset( $values['my_meta_box_text'] ) ? esc_attr( $values['my_meta_box_text'][0] ) : â;
$selected = isset( $values['my_meta_box_select'] ) ? esc_attr( $values['my_meta_box_select'][0] ) : â;
$check = isset( $values['my_meta_box_check'] ) ? esc_attr( $values['my_meta_box_check'][0] ) : â;
wp_nonce_field( plugin_basename( __FILE__ ), 'testimonial_text_box_content_nonce' );
$value = get_post_meta( $post->ID, '_my_meta_value_key', true );
echo '<label for="testimonial_text">';
_e("Text body of the testimonial:", 'myplugin_textdomain' );
echo '</label> ';
echo '<br/>';
echo '<textarea align="top" id="testimonial_text" name="testimonial_text" value="'.esc_attr($value).'" style="width:100%;height:200px;margin:5px -20px 3px 0;" /></textarea>';
}
add_action( 'save_post', 'testimonial_text_box_save' );
function testimonial_text_box_save( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['testimonial_text_box_content_nonce'], plugin_basename( __FILE__ ) ) )
return;
if ( 'testimonial' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
$testimonial_text = $_POST['testimonial_text'];
update_post_meta( $post_id, 'testimonial_text', $testimonial_text );
}
Problems with your code:
Unnecessary block (it’s not related to the goal at hand):
You’re saving
testimonial_text
with:but getting
_my_meta_value_key
with:Change the
get_
totestimonial_text
.A
textarea
doesn’t havevalue
, the content goes inside the open/close tags:The hook
save_post
takes 2 arguments:There’s a non-working if/else that should be like:
To use the post meta in the front end, just use
get_post_meta()
.