$post_id or $post->ID in wordpress meta box construction -
can explain why when creating meta boxes callback needs post id passed via $post->id, action hook 'save_post', function can pass $post_id. general explanation of when use 1 clear issues i've been having, thanks.
ex:
function show_custom_meta_box($post) { $meta = get_post_meta($post->id, 'custom_meta_class', true); // use nonce verification echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__file__)).'" />'; // begin field table , loop echo '<table class="form-table">'; echo '<tr> <th><label for="custom-meta-class">custom meta box</label></th> <td> <input class="widefat" type="text" name="custom-meta-class" id="custom-meta-class" value="'.$meta.'" size="50" />'; echo '</td></tr>'; echo '</table>'; // end table }
and $post_id
function save_custom_meta($post) { if( defined( 'doing_autosave' ) && doing_autosave ) return; /* verify nonce before proceeding. */ if ( !isset( $_post['custom_meta_box_nonce'] ) || !wp_verify_nonce( $_post['custom_meta_box_nonce'], basename( __file__ ) ) ) return $post_id; $post_type = get_post_type_object( $post->post_type ); /* check if current user has permission edit post. */ if ( !current_user_can( $post_type->cap->edit_post, $post_id ) ) return $post_id; /* posted data , sanitize use html class. */ $new_meta_value = ( isset( $_post['custom-meta-class'] ) ? sanitize_html_class( $_post['custom-meta-class'] ) : '' ); /* meta key. */ $meta_key = 'custom_meta_class'; /* meta value of custom field key. */ $meta_value = get_post_meta( $post_id, $meta_key, true ); if ( $new_meta_value && '' == $meta_value ) add_post_meta( $post_id, $meta_key, $new_meta_value, true ); /* if new meta value not match old value, update it. */ elseif ( $new_meta_value && $new_meta_value != $meta_value ) update_post_meta( $post_id, $meta_key, $new_meta_value ); /* if there no new meta value old value exists, delete it. */ elseif ( '' == $new_meta_value && $meta_value ) delete_post_meta( $post_id, $meta_key, $meta_value ); }
the action hook save_post returns $post_id.
show_custom_meta_box
not wordpress hook, custom function. uses get_post_meta , function requires $post_id
.
there no need give $post. can edit code uses id, not post object:
function show_custom_meta_box($post_id) { $meta = get_post_meta($post_id, 'custom_meta_class', true); }
Comments
Post a Comment