过了一段时间,我发现了如何解决我的问题。
简而言之,我必须使用Javascript打开WP媒体上传程序。在我的选项中,我只保存附件ID。
这是我的代码:
HTML/PHP:
<?php
$options = get_option( \'mysettings\' );
$image_id = esc_attr__( $options[\'image_id\']);
?>
<div id="logo">
<?php
$hasImage = false;
$image = wp_get_attachment_image_src( $image_id, \'medium\' );
$image_url = $image[0];
if (!is_null($image_id) && $image_id !== "" && $image_id > 0) {
$hasImage = true;
}
?>
<div>
<label for="image_url">Image</label>
<input type="hidden" name="mysettings[image_id]" id="option_image_id" class="regular-text">
<input id="upload_img-btn" type="button" name="upload-btn" class="button-secondary" value="Upload Image">
</div>
<div id="logo_container">
<?php if ($hasImage) { ?>
<img class="logo" src="<?php echo $image_url; ?>" />
<?php } ?>
</div>
<input id="delete_img-btn" type="button" name="delete-btn" class="button-secondary" value="Remove Image" <?php if (!$hasImage) echo \'style="display: none;"\'; ?>>
</div>
和我的Javascript代码:
jQuery(document).ready(function($) {
$("#delete_img-btn").on("click", function(e) {
e.preventDefault();
$(\'#logo_container\').html("");
$("#delete_img-btn").hide();
});
$(\'#upload_img-btn\').on("click", function(e) {
e.preventDefault();
var $el = jQuery( this );
var optionImageFrame = wp.media({
title: $el.data( \'choose\' ),
button: {
text: $el.data( \'update\' )
},
states: [
new wp.media.controller.Library({
title: $el.data( \'choose\' ),
filterable: \'all\',
// mutiple: true if you want to upload multiple files at once
multiple: false
})
]
});
optionImageFrame.on(\'select\', function(e){
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_image = optionImageFrame.state().get(\'selection\').first();
// We convert uploaded_image to a JSON object to make accessing it easier
// Output to the console uploaded_image
var attachment = uploaded_image.toJSON();
var image_url = attachment.url;
var image_id = attachment.id;
$(\'#option_image_id\').val(image_id);
$(\'#logo_container\').append(\'<img class="logo" src="\' + image_url + \'" />\');
$("#delete_img-btn").show();
});
optionImageFrame.open();
});
});