这是WordPress插件,我想在从媒体库中选择图像后进行图像预览,
$my_saved_attachment_post_id = get_option('media_selector_attachment_id',0);
?>
<script type="text/javascript">
jQuery(document).ready(function($){
//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 = <?php echo $my_saved_attachment_post_id;?>;
jQuery('#upload_image_button').on('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 {
wp.media.model.settings.post.id = set_to_post_id;
}
//create the media frame
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple:false
});
file_frame.on('select', function () {
attachment = file_frame.state().get('selection').first().toJSON();
$('#image-preview').attr('src',attachment.url).css('width','auto');
$('#image-attachment-id').val(attachment.id);
wp.media.model.settings.post.id = wp_media_post_id;
});
file_frame.open();
});
jQuery('a.add-media').on('click', function(){
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script>
if (isset($_POST['save-details']) && isset($_POST['image-attachment-id'])):
update_option('media_selector_attachment_id', absint($_POST['image-attachment-id']));
endif;
<div class="img-preview-wrapper">
<img id="img-preview" src="<?php echo wp_get_attachment_url(get_option('media_selector_attachment_id')); ?>" height="100px"/>
</div><br>
<input id="upload_image_button" type="button" class="btn btn-default btn-lg" value="Upload Image"/>
<input type="hidden" name="image-attachment-id" id="image-attachment-id" value="<?php echo get_option('media_selector_attachment_id'); ?>"/>
<input type="submit" name="save-details" value="Save" class="btn btn-default btn-lg"/>
在此代码中,单击“保存”按钮后显示预览,任何人都可以告诉我,如何在选择图像后立即进行预览。