透過自定義欄位給文章新增一些附屬圖片什麼的,應用很廣,一般技術不到位的,會使用自定義欄位填寫圖片 url 來實現,那樣雖然實現了,但是非常不方便,我們要的是不經能直接填寫圖片 url,而且能直接上傳,並且要能夠即時預覽。其實理論很簡單,跟我們後臺教程中新增圖片上傳功能基本一樣,可參考:WordPress 主題後臺製作 (八): 圖片上傳。
OK,我們還是沿用上一篇教程中的程式碼,並且直接在上一篇教程中新增圖片上傳功能:
首先開啟我們的 metabox.php 檔案,在配置陣列中新增一項:
- "uploads" => array(
- "name" => "_meta_uploader",
- "std" => '',
- "title" => "圖片上傳",
- "type"=>"uploader"),
第二步:在函式 new_meta_boxes 中的 switch 語句中新增一項即可,其實我們直接將後臺教程中提到的上傳程式碼複製過來即可用:
- case 'uploader':
- echo'<h4>'.$meta_box['title'].'</h4>';
- //圖片預覽框
- if($meta_box['std'] != ''){
- echo '<span id="'.$meta_box['name'].'_value_img"><img src='.$meta_box['std'].' alt="" /></span>';}
- echo '<input class="ashu_upload_input" type="text" size="40" value="'.$meta_box['std'].'" name="'.$meta_box['name'].'_value"/>';
- echo '<input type="button" value="上傳" class="ashu_bottom"/>';
- echo '<br/>';
- break;
第三步:載入 js,要知道,如果僅僅加這個程式碼,雖然你能夠調取到上傳圖片上傳的對話方塊,但是還不能將圖片 url 插入到文字域中,更不能實現即時預覽。所以我們需要新增一個 js 檔案,比如我沿用以前的,在 twenty ten 主題中新建一個 js 資料夾,在裡面加你一個名為 metaup.js 的 js 檔案,該 js 檔案中的程式碼為:
- jQuery(document).ready(function() {
- jQuery('input.ashu_bottom').click(function() {
- custom_editor = true;
- targetfield = jQuery(this).prev('input');
- tb_show('', 'media-upload.php?type=image&TB_iframe=true');
- window.original_send_to_editor = window.send_to_editor;
- window.send_to_editor = function(html) {
- if (custom_editor) {
- imgurl = jQuery('img',html).attr('src');
- jQuery(targetfield).val(imgurl).focus();
- custom_editor = false;
- tb_remove();
- }else{
- window.original_send_to_editor(html);
- }
- }
- return false;
- });
- //圖片即時預覽 ashu_upload_input 為圖片 url 文字框的 class 屬性
- jQuery('input.ashu_upload_input').each(function()
- {
- jQuery(this).bind('change focus blur', function()
- {
- //獲取改文字框的 name 屬性後面
- $select = '#' + jQuery(this).attr('name') + '_img';
- $value = jQuery(this).val();
- $image = '<img src ="'+$value+'" />';
- var $image = jQuery($select).html('').append($image).find('img');
- //set timeout because of safari
- window.setTimeout(function()
- {
- if(parseInt($image.attr('width')) < 20)
- {
- jQuery($select).html('');
- }
- },500);
- });
- });
- });
第四步:載入 js 檔案,在 metabox.php 檔案的函式中 (請注意是在該函式中,不在 switch 語句的外面, 或者你也可以直接放在這個檔案中,不放在任何函式裡面) 新增以下程式碼:
- wp_enqueue_script('kriesi_custom_fields_js', get_template_directory_uri(). '/js/metaup.js');
這樣就完成了,效果圖:

呼叫方法請參考上一篇文章。
好了,為了方便懶人使用,將現在的 metabox.php 中的程式碼全部貼出,注意現在新增 js 檔案才能使用哦。
- <?php
- $new_meta_boxes =
- array(
- "title" => array(
- "name" => "_meta_title",
- "std" => "",
- "title" => "標題",
- "type"=>"title"),
- "keywords" => array(
- "name" => "_meta_keywords",
- "std" => "",
- "title" => "關鍵字",
- "type"=>"text"),
- "description" => array(
- "name" => "_meta_description",
- "std" => "",
- "title" => "描述%