Это можно использовать встроенную загрузку WordPress Media в своих функциях темы. Я успешно включил его во многие темы и во множество различных применений.
Ниже приведена простая версия (у меня есть другая версия, которая поддерживает несколько полей для загрузки изображений на одной странице).
В файле JavaScript (сохраните как media_upload.js в каталоге вашей темы):
var formfield, tbframe_interval;
jQuery(document).ready(function() {
// Bind the click to your upload image button
jQuery('.upload_image_button').click(function() {
// Which gets the name of the input field
formfield = '.image_input';
tb_show('', 'media-upload.php?post_id=0&type=image&TB_iframe=1');
// Set an interval to change the button text from Insert Into Post
tbframe_interval = setInterval(function() {
jQuery('#TB_iframeContent').contents().find('.savesend .button').val('Use This Image');
}, 2000);
return false;
});
// Bind event to the focus of the input field to trigger the media upload
jQuery('.image_input').focus(function() {
jQuery('.upload_image_button').trigger("click");
});
// Bind click event to the delete button if it is already displayed
jQuery("#preview_image .delete").click(function() {removeImage();});
// Get original send to editor because we are about to override it
window.original_send_to_editor = window.send_to_editor;
// Custom function to override where media upload sends data
window.send_to_editor = function(html) {
// If formfield set, means we're using our custom function
if (formfield) {
// Have to add tags around html in order to be sure finds img src
imgurl = jQuery('img','<p>' + html + '</p>').attr('src');
// Send the img url to the input field
jQuery(formfield).val(imgurl);
// Remove the media upload box
tb_remove();
// Call our function to display image
renderImage(imgurl);
// Clear the formfield
formfield = "";
// Clear the interval that changes the button name
clearInterval(tbframe_interval);
// If not, use the original function
} else {
window.original_send_to_editor(html);
}
}
});
// function to load the image url into the correct input box
function renderImage(img) {
// Load the image into the div we set up to display it
// Also throws in a delete button to remove the image
jQuery("#preview_image").html('<img src="' + img + '" alt="" /><a class="delete" title="Remove Image" href="javascript:void(0);">X</a>');
// Bind the click to the delete in order to remove the image
jQuery("#preview_image .delete").click(function() {removeImage();});
}
// Function we call when the delete button is clicked
function removeImage() {
jQuery("#preview_image").html('');
jQuery('.image_input').val('');
}
В файле functions.php вашей темы вы должны поставить в очередь необходимые сценарии (включая приведенный выше), создав функцию и используя хуки WP для вызова функции в admin int:
function my_theme_media_script_load() {
// Load the necessary WP scripts
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
// Register our custom script
wp_register_script('my-custom-media-upload', get_bloginfo("template_url") .
'/javascript/media_upload.js', array('jquery','media-upload','thickbox'));
// Load our custom script
wp_enqueue_script('my-custom-media-upload');
// Load the WP style for the media upload thickbox
wp_enqueue_style('thickbox');
}
add_action ('admin_init', 'my_theme_media_script_load');
И, наконец, там, где вы хотите, чтобы отображались поля ввода загрузки мультимедиа и предварительный просмотр, используйте следующий html:
<?php
// Provide your own code to load the image url into the variable $image
// Then prepare a couple of variables for displaying the image and delete in the html
$preview = ($image) ? '<img src="' . $image . '" alt="" />' : '';
$delete_button = ($image) ? '<a class="delete" href="javascript:void(0);" title="Remove Image"><img src="' . get_bloginfo("template_url") . '/images/delete.png" alt="X" /></a>' : '';
?>
<div class="media">
<label for="acg_user_photo">Image:</label>
<input type="text" class="image_input" id="image_input" name="image_upload" value="<?php echo $image; ?>" />
<input type="button" class="upload_image_button" name="image_button" value="Upload" />
<div class="preview" id="preview_image">
<?php echo $delete_button; ?>
<p id="preview"><?php echo $preview; ?></p>
</div>
</div>
Вы должны предоставить CSS, чтобы он выглядел хорошо.
Также обратите внимание, что это только должно выполняться на стороне администратора. Вы не можете доверять среднестатистическому посетителю загружать что-либо на ваш сайт.