案例:我使用图像采集器。js脚本为我的自定义元框创建图像选择器。但这对WP 3.6已经不起作用了,所以我尝试用新的媒体上传器创建一个图像选择器元盒。
我将其用于JSON对象,但如何将这些属性从JSON对象保存到metabox?
jQuery图像选择器:
jQuery(function(jQuery) {
// Uploading files
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = 5; // Set this
formfield = jQuery(this).siblings(\'.custom_upload_image\');
preview = jQuery(this).siblings(\'.custom_preview_image\');
jQuery(\'.custom_upload_image_button\').live(\'click\', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
// Set the post ID to what we want
file_frame.uploader.uploader.param( \'post_id\', set_to_post_id );
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: jQuery( this ).data( \'uploader_title\' ),
button: {
text: jQuery( this ).data( \'uploader_button_text\' ),
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( \'select\', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get(\'selection\').first().toJSON();
// Do something with attachment.id and/or attachment.url here
console.log(attachment.url);
console.log(attachment.id);
imgurl = attachment.url;
id = attachment.id;
formfield.val(id);
preview.attr(\'src\', imgurl);
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
jQuery(\'a.add_media\').on(\'click\', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
我的猜测是,这其中必须添加一些内容:
// Save data from meta box
function save($post_id) {
// verify nonce
if (!wp_verify_nonce($_POST[\'mytheme_meta_box_nonce\'], basename(__FILE__))) {
return $post_id;
}
// check autosave
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) {
return $post_id;
}
// check permissions
if (\'page\' == $_POST[\'post_type\']) {
if (!current_user_can(\'edit_page\', $post_id)) {
return $post_id;
}
} elseif (!current_user_can(\'edit_post\', $post_id)) {
return $post_id;
}
foreach ($this->_meta_box[\'fields\'] as $field) {
$old = get_post_meta($post_id, $field[\'id\'], true);
$new = $_POST[$field[\'id\']];
if ($new && $new != $old) {
update_post_meta($post_id, $field[\'id\'], $new);
} elseif (\'\' == $new && $old) {
delete_post_meta($post_id, $field[\'id\'], $old);
}
elseif ($new == \'\') {
delete_post_meta($post_id, $field[\'id\'], $old);
}
}
}