大家在制作WordPress插件(插件)的设定页面时可能会需要添加一些类似「上传图片」的按钮,所以今天就来教大家如何给WordPress插件设定页面添加「上传」功能
教学
1、首先我们需要引用所有需要的文件,所以在你的插件设定代码之前添加下列代码(注意将 my-plugin
更改为你插件的Text-Domain)
1 2 3 4 5 6 7 8 9 |
function my_plugin_admin_script(){ if (isset($_GET['page']) && $_GET['page'] == 'my-plugin-options'){ wp_register_script('my-plugin-upload', plugin_dir_url( __FILE__ ).'admin-script.js', array('jquery','media-upload','thickbox')); wp_enqueue_script('my-plugin-options'); wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); } } add_action('admin_print_scripts', 'my_plugin_admin_script'); |
2、在插件根目录下新建一个叫「admin-script.js」的文件,并且在里面加入下列内容(注意将 #my_plugin_upload_url
及 .my-plugin-upload-button
改成适当的名称或ID)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/** Plugin Option Page Upload File By Arefly.com **/ jQuery(document).ready(function() { var formfield; /* user clicks button on custom field, runs below code that opens new window */ jQuery('.my-plugin-upload-button').click(function() { formfield = jQuery("#my_plugin_upload_url"); //The input field that will hold the uploaded file url tb_show('', 'media-upload.php?TB_iframe=true'); return false; }); //adding my custom function with Thick box close function tb_close() . window.old_tb_remove = window.tb_remove; window.tb_remove = function() { window.old_tb_remove(); // calls the tb_remove() of the Thickbox plugin formfield=null; }; // user inserts file into post. only run custom if user started process using the above process // window.send_to_editor(html) is how wp would normally handle the received data window.original_send_to_editor = window.send_to_editor; window.send_to_editor = function(html){ if (formfield) { fileurl = jQuery('img',html).attr('src'); jQuery(formfield).val(fileurl); tb_remove(); } else { window.original_send_to_editor(html); } }; }); |
3、在你的插件设定页面的HTML代码中添加下列内容(同样注意将 #my_plugin_upload_url
及 .my-plugin-upload-button
改成适当的名称或ID)
1 2 |
<input id="my_plugin_upload_url" type="text" name="my_plugin_upload_url" size="50" /> <input class="my-plugin-upload-button button" type="button" value="Upload File" /> |
参考资料
How to use WordPress Media Uploader in Plugin or Theme Admin page