好了,问题来了,这是保存数据的完整代码。下面对这些问题进行了解释:
/**
* Adds a box to the main column on the Post and Page edit screens.
*/
function nss_mood_add_meta_box() {
//$id, $title, $callback, $post_type, $context,$priority, $callback_args
add_meta_box(\'nss_mood_id\',\'Set your mood\',\'nss_mood_cb\',\'post\');
}
add_action(\'add_meta_boxes\',\'nss_mood_add_meta_box\');
// Dispalying form and taking input
function nss_mood_cb() {
global $post;
echo \'<input type="hidden" name="mood_meta_box_nonce" value="\'.wp_create_nonce(basename(__FILE__)).\'" />\';
$mood_value = get_post_meta( $post->ID, \'mood_value_key\', true );
// Creating our form
echo \'<p>\';
echo \'<label for="mood_value_key">What is your mood today ? </label></br></br>\';
echo \'<input type="text" class="widefat" name="mood_value_key" id="mood_value_key" value="\' . esc_attr( $mood_value ) . \'" />\';
echo \'</p>\';
}
// Checking value of the form and updating
function save_nss_mood_data($post_id) {
/*
* We need to verify this came from our screen and with proper authorization,
* because the save_post action can be triggered at other times.
*/
// Check if our nonce is set.
if ( empty( $_POST[\'mood_meta_box_nonce\'] ) || !wp_verify_nonce( $_POST[\'mood_meta_box_nonce\'], basename(__FILE__)) ) return;
// If this is an autosave, our form has not been submitted, so we don\'t want to do anything.
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user\'s permissions.
if ( isset( $_POST[\'post_type\'] ) ) {
if ( ! current_user_can( \'edit_post\', $post_id ) ) {
return;
}
}
/* OK, it\'s safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST[\'mood_value_key\'] ) ) {
return;
}
// Sanitize user input.
$mood_data = sanitize_text_field( $_POST[\'mood_value_key\'] );
// Update the meta field in the database.
update_post_meta( $post_id, \'mood_value_key\', $mood_data );
}
add_action(\'save_post\',\'save_nss_mood_data\');
引起干扰的问题:
您的功能nss_mood_cb()
需要$post->ID
但是没有$post
那里所以你需要$post
变量,我使用global $post
.您的临时发送不正确。您正在创建nonce,但实际上没有发送到save函数。我在那里添加了一个隐藏输入,它将nonce发送到save函数
英寸save_nss_mood_data()
我用一种更聪明的方法检查了nonce而且,正如我已经评论的那样isset( $_POST[\'mood_field\'] )
事情不对,所以我改成isset( $_POST[\'mood_value_key\'] )
因为这实际上来自nss_mood_cb()
回调函数