更好的标题是:如何使用WordPress媒体上传器将图像上传到设置页面。
1-添加必要的脚本以显示媒体上载程序:
add_action(\'admin_footer\', function() {
/*
if possible try not to queue this all over the admin by adding your settings GET page val into next
if( empty( $_GET[\'page\'] ) || "my-settings-page" !== $_GET[\'page\'] ) { return; }
*/
?>
<script>
jQuery(document).ready(function($){
var custom_uploader
, click_elem = jQuery(\'.wpse-228085-upload\')
, target = jQuery(\'.wrap input[name="logo"]\')
click_elem.click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: \'Choose Image\',
button: {
text: \'Choose Image\'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field\'s value
custom_uploader.on(\'select\', function() {
attachment = custom_uploader.state().get(\'selection\').first().toJSON();
target.val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
</script>
<?php
});
2-嵌入媒体上载程序所需的脚本:
add_action(\'admin_enqueue_scripts\', function(){
/*
if possible try not to queue this all over the admin by adding your settings GET page val into next
if( empty( $_GET[\'page\'] ) || "my-settings-page" !== $_GET[\'page\'] ) { return; }
*/
wp_enqueue_media();
});
3-现在在图像字段旁边添加一个可单击的按钮,以调用媒体上载程序:
<input type="file" name="logo" />
<button class="button wpse-228085-upload">Upload</button>
上传器工作后,现在可以处理图像字段(
input[name="logo"]
) 与任何其他设置字段一样,并将其值保存到您的选项中。
希望这有帮助。