大家在製作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