通過自定義字段給文章添加一些附屬圖片什麼的,應用很廣,一般技術不到位的,會使用自定義字段填寫圖片 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" => "描述%