我尝试了你的代码,它可以工作:
我改变了wp_verify_nonce
功能,因为这对我不起作用。我添加了一个操作,而不是它所具有的操作。现在,要使其工作,您必须创建一个nonce字段,其中包含这样的代码,当然,如果需要,您可以更改名称。
//this goes in the function that generates the metabox
wp_nonce_field( \'location_map_nonce_action\', \'location_map_nonce\' );
这是保存值的函数的最终代码。
function kk_save_location_map( $post_id, $post ) {
/* Verify the nonce before proceeding. */
if ( !isset( $_POST[\'location_map_nonce\'] ) || !wp_verify_nonce( $_POST[\'location_map_nonce\'], \'location_map_nonce_action\' ) ){
return $post_id;
}
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) ){
return $post_id;
}
/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = ( isset( $_POST[\'location-map\'] ) ? ( $_POST[\'location-map\'] ) : \'\' );
/* Get the meta key. */
$meta_key = \'location-map\';
/* Get the meta value of the custom field key. */
$meta_value = esc_textarea(get_post_meta( $post_id, $meta_key, true ));
/* If a new meta value was added and there was no previous value, add it. */
if ( $new_meta_value && \'\' == $meta_value ){
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
}
/* If the new meta value does not match the 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 is no new meta value but an old value exists, delete it. */
elseif ( \'\' == $new_meta_value && $meta_value ){
delete_post_meta( $post_id, $meta_key, $meta_value );
}
}
add_action( \'save_post\', \'kk_save_location_map\', 10, 2 );