wordpress进阶教程(十):后台创建自定义面板类文件

丢了这么多天没更新教程了,自己写到哪里都快忘了。。

前面几篇教程演示了如何在wordpress后台文章编辑页面添加自定义面板,今天的这篇文章不能算教程,和wordpress后台教程的结尾一样,直接放出一个便于使用的类文件,实际使用的时候只需要包含这个类文件,然后加载配置文件即可使用。

使用该类文件可以创建标题、文本框、文本域、下拉框、复选框、图片实时预览上传。不过少了单选框(radio)和文本编辑器,因为个人很少用到这两个,所以就没加上,如果有需要的,完全可以参照我们前面几篇教程自己添加上。

说实话,这个类文件也不完全是我写的,我也是从一个主题上弄来的,然后修改。

文件下载(压缩包内功四个文件,分别是类文件、配置文件、js文件、css文件)

懒人下载

版本控制

2013.07.08,版本1.0

  1. 修改复选框功能
  2. 增加编辑器功能

类文件metaboxclass.php:

  1. <?php   
  2. /*
  3. wordpress文章自定义字段类文件  
  4. Version: 1.0  
  5. Author: 树是我的朋友  
  6. Author URI: http://www.ashuwp.com  
  7. License: http://www.ashuwp.com/courses/highgrade/298.html  
  8. */  
  9. class ashu_meta_box{   
  10.     var $options;   
  11.     var $boxinfo;   
  12.        
  13.     //构造函数   
  14.     function ashu_meta_box($options,$boxinfo){   
  15.         $this->options = $options;   
  16.         $this->boxinfo = $boxinfo;   
  17.            
  18.         add_action('admin_menu', array(&$this, 'init_boxes'));   
  19.         add_action('save_post', array(&$this, 'save_postdata'));   
  20.     }   
  21.        
  22.     //初始化   
  23.     function init_boxes(){   
  24.         $this->add_script_and_styles();   
  25.         $this->create_meta_box();   
  26.     }   
  27.        
  28.     //加载css和js脚本   
  29.     function add_script_and_styles(){   
  30.         if(basename$_SERVER['PHP_SELF']) == "page.php"    
  31.         || basename$_SERVER['PHP_SELF']) == "page-new.php"    
  32.         || basename$_SERVER['PHP_SELF']) == "post-new.php"    
  33.         || basename$_SERVER['PHP_SELF']) == "post.php"  
  34.         || basename$_SERVER['PHP_SELF']) == "media-upload.php")   
  35.         {      
  36.             //注意加载的脚本的url   
  37.             wp_enqueue_style('metabox_fields_css', TEMJS_URI. 'metabox_fields.css');   
  38.             wp_enqueue_script('metabox_fields_js',TEMJS_URI. 'metabox_fields.js');   
  39.             wp_enqueue_style('thickbox');   
  40.             wp_enqueue_script('media-upload');   
  41.             wp_enqueue_script('thickbox');   
  42.                
  43.   
  44.             if(isset($_GET['hijack_target']))   
  45.             {      
  46.                 add_action('admin_head', array(&$this,'add_hijack_var'));   
  47.             }   
  48.         }   
  49.     }   
  50.        
  51.     /*************************/  
  52.     function add_hijack_var()   
  53.     {   
  54.         echo "<meta name='hijack_target' content='".$_GET['hijack_target']."' />\n";   
  55.     }   
  56.        
  57.     //创建自定义面板   
  58.     function create_meta_box(){   
  59.         if ( function_exists('add_meta_box') && is_array($this->boxinfo['page']) )    
  60.         {   
  61.             foreach ($this->boxinfo['page'] as $area)   
  62.             {      
  63.                 if ($this->boxinfo['callback'] == ''$this->boxinfo['callback'] = 'new_meta_boxes';   
  64.                    
  65.                 add_meta_box(      
  66.                     $this->boxinfo['id'],    
  67.                     $this->boxinfo['title'],   
  68.                     array(&$this$this->boxinfo['callback']),   
  69.                     $area$this->boxinfo['context'],    
  70.                     $this->boxinfo['priority']   
  71.                 );     
  72.             }   
  73.         }     
  74.     }   
  75.        
  76.     //创建自定义面板的显示函数   
  77.     function new_meta_boxes(){   
  78.         global $post;   
  79.         //根据类型调用显示函数   
  80.         foreach ($this->options as $option)   
  81.         {                  
  82.             if (method_exists($this$option['type']))   
  83.             {   
  84.                 $meta_box_value = get_post_meta($post->ID, $option['id'], true);    
  85.                 if($meta_box_value != ""$option['std'] = $meta_box_value;     
  86.                    
  87.                 echo '<div class="alt kriesi_meta_box_alt meta_box_'.$option['type'].' meta_box_'.$this->boxinfo['context'].'">';   
  88.                 $this->$option['type']($option);   
  89.                 echo '</div>';   
  90.             }   
  91.         }   
  92.            
  93.         //隐藏域   
  94.         echo'<input type="hidden" name="'.$this->boxinfo['id'].'_noncename" id="'.$this->boxinfo['id'].'_noncename" value="'.wp_create_nonce( 'ashumetabox' ).'" />';     
  95.     }   
  96.        
  97.     //保存字段数据   
  98.     function save_postdata() {   
  99.         if( isset( $_POST['post_type'] ) && in_array($_POST['post_type'],$this->boxinfo['page'] ) && (isset($_POST['save']) || isset($_POST['publish']) ) ){   
  100.         $post_id = $_POST['post_ID'];   
  101.            
  102.         foreach ($this->options as $option) {   
  103.             if (!wp_verify_nonce($_POST[$this->boxinfo['id'].'_noncename'], 'ashumetabox')) {      
  104.                 return $post_id ;   
  105.             }   
  106.             //判断权限   
  107.             if ( 'page' == $_POST['post_type'] ) {   
  108.                 if ( !current_user_can( 'edit_page', $post_id  ))   
  109.                 return $post_id ;   
  110.             } else {   
  111.                 if ( !current_user_can( 'edit_post', $post_id  ))   
  112.                 return $post_id ;   
  113.             }   
  114.             //将预定义字符转换为html实体   
  115.             if$option['type'] == 'tinymce' ){   
  116.                     $data =  stripslashes($_POST[$option['id']]);   
  117.             }elseif$option['type'] == 'checkbox' ){   
  118.                     $data =  $_POST[$option['id']];   
  119.             }else{   
  120.                 $data = htmlspecialchars($_POST[$option['id']], ENT_QUOTES,"UTF-8");   
  121.             }   
  122.                
  123.             if(get_post_meta($post_id , $option['id']) == "")   
  124.             add_post_meta($post_id , $option['id'], $data, true);   
  125.                
  126.             elseif($data != get_post_meta($post_id , $option['id'], true))   
  127.             update_post_meta($post_id , $option['id'], $data);   
  128.                
  129.             elseif($data == "")   
  130.             delete_post_meta($post_id , $option['id'], get_post_meta($post_id , $option['id'], true));   
  131.                
  132.         }   
  133.         }   
  134.     }   
  135.     //显示标题   
  136.     function title($values){   
  137.         echo '<p>'.$values['name'].'</p>';   
  138.     }   
  139.     //文本框   
  140.     function text($values){    
  141.         if(isset($this->database_options[$values['id']])) $values['std'] = $this->database_options[$values['id']];   
  142.            
  143.         echo '<p>'.$values['name'].'</p>';   
  144.         echo '<p><input type="text" size="'.$values['size'].'" value="'.$values['std'].'" id="'.$values['id'].'" name="'.$values['id'].'"/>';   
  145.         echo $values['desc'].'<br/></p>';   
  146.         echo '<br/>';   
  147.     }   
  148.     //文本域   
  149.     function textarea($values){   
  150.         if(isset($this->database_options[$values['id']])) $values['std'] = $this->database_options[$values['id']];   
  151.            
  152.         echo '<p>'.$values['name'].'</p>';   
  153.         echo '<p><textarea class="kriesi_textarea" cols="60" rows="5" id="'.$values['id'].'" name="'.$values['id'].'">'.$values['std'].'</textarea>';   
  154.         echo $values['desc'].'<br/></p>';   
  155.         echo '<br/>';   
  156.     }   
  157.     //媒体上传   
  158.     function media($values){   
  159.         if(isset($this->database_options[$values['id']])) $values['std'] = $this->database_options[$values['id']];   
  160.            
  161.         //图片上传按钮   
  162.         global $post_ID$temp_ID;   
  163.         $uploading_iframe_ID = (int) (0 == $post_ID ? $temp_ID : $post_ID);   
  164.         $media_upload_iframe_src = "media-upload.php?post_id=$uploading_iframe_ID";   
  165.         $image_upload_iframe_src = apply_filters('image_upload_iframe_src', "$media_upload_iframe_src&amp;type=image");   
  166.            
  167.         $button = '<a href="'.$image_upload_iframe_src.'&amp;hijack_target='.$values['id'].'&amp;TB_iframe=true" id="'.$values['id'].'" class="k_hijack button thickbox" onclick="return false;" >上传</a>';   
  168.            
  169.         //判断图片格式,图片预览   
  170.         $image = '';   
  171.         if($values['std'] != '') {   
  172.             $fileextension = substr($values['std'], strrpos($values['std'], '.') + 1);   
  173.             $extensions = array('png','gif','jpeg','jpg','pdf','tif');   
  174.                
  175.             if(in_array($fileextension$extensions))   
  176.             {   
  177.                 $image = '<img src="'.$values['std'].'" />';   
  178.             }   
  179.         }   
  180.            
  181.         echo '<div id="'.$values['id'].'_div" class="kriesi_preview_pic">'.$image .'</div>';   
  182.         echo '<p>'.$values['name'].'</p><p>';   
  183.         if($values['desc'] != ""echo '<p>'.$values['desc'].'<br/>';   
  184.         echo '<input class="kriesi_preview_pic_input" type="text" size="'.$values['size'].'" value="'.$values['std'].'" name="'.$values['id'].'"/>'.$button;   
  185.         echo '</p>';   
  186.         echo '<br/>';   
  187.     }   
  188.     //单选框   
  189.     function radio( $values ){   
  190.         if(isset($this->database_options[$values['id']]))   
  191.             $values['std'] = $this->database_options[$values['id']];   
  192.         echo '<p>'.$values['name'].'</p>';   
  193.         foreach$values['buttons'] as $key=>$value ) {   
  194.             $checked ="";   
  195.             if($values['std'] == $key) {   
  196.                 $checked = 'checked = "checked"';   
  197.             }   
  198.             echo '<input '.$checked.' type="radio" class="kcheck" value="'.$key.'" name="'.$values['id'].'"/>'.$value;   
  199.         }   
  200.     }   
  201.     //复选框   
  202.     function checkbox($values){   
  203.         echo '<p>'.$values['name'].'</p>';   
  204.         foreach$values['buttons'] as $key=>$value ) {   
  205.             $checked ="";   
  206.             ifis_array($values['std']) && in_array($key,$values['std'])) {   
  207.                 $checked = 'checked = "checked"';   
  208.             }   
  209.             echo '<input '.$checked.' type="checkbox" class="kcheck" value="'.$key.'" name="'.$values['id'].'[]"/>'.$value;   
  210.         }   
  211.         echo '<label for="'.$values['id'].'">'.$values['desc'].'</label><br/></p>';   
  212.     }   
  213.     //下拉框   
  214.     function dropdown($values){   
  215.         echo '<p>'.$values['name'].'</p>';   
  216.             //选择内容可以使页面、分类、菜单、侧边栏和自定义内容   
  217.             if($values['subtype'] == 'page'){   
  218.                 $select = 'Select page';   
  219.                 $entries = get_pages('title_li=&orderby=name');   
  220.             }else if($values['subtype'] == 'cat'){   
  221.                 $select = 'Select category';   
  222.                 $entries = get_categories('title_li=&orderby=name&hide_empty=0');   
  223.             }else if($values['subtype'] == 'menu'){   
  224.                 $select = 'Select Menu in page left';   
  225.                 $entries = get_terms( 'nav_menu', array( 'hide_empty' => false ) );   
  226.             }else if($values['subtype'] == 'sidebar'){   
  227.                 global $wp_registered_sidebars;   
  228.                 $select = 'Select a special sidebar';   
  229.                 $entries = $wp_registered_sidebars;   
  230.             }else{     
  231.                 $select = 'Select...';   
  232.                 $entries = $values['subtype'];   
  233.             }   
  234.            
  235.             echo '<p><select class="postform" id="'. $values['id'] .'" name="'. $values['id'] .'"> ';   
  236.             echo '<option value="">'.$select .'</option>  ';   
  237.                
  238.             foreach ($entries as $key => $entry){   
  239.                 if($values['subtype'] == 'page'){   
  240.                     $id = $entry->ID;   
  241.                     $title = $entry->post_title;   
  242.                 }else if($values['subtype'] == 'cat'){   
  243.                     $id = $entry->term_id;   
  244.                     $title = $entry->name;   
  245.                 }else if($values['subtype'] == 'menu'){   
  246.                     $id = $entry->term_id;   
  247.                     $title = $entry->name;   
  248.                 }else if($values['subtype'] == 'sidebar'){   
  249.                     $id = $entry['id'];   
  250.                     $title = $entry['name'];   
  251.                 }else{   
  252.                     $id = $entry;   
  253.                     $title = $key;                 
  254.                 }   
  255.   
  256.                 if ($values['std'] == $id ){   
  257.                     $selected = "selected='selected'";     
  258.                 }else{   
  259.                     $selected = "";        
  260.                 }   
  261.                    
  262.                 echo"<option $selected value='"$id."'>"$title."</option>";   
  263.             }   
  264.            
  265.         echo '</select>';   
  266.         echo $values['desc'].'<br/></p>';    
  267.         echo '<br/>';   
  268.     }   
  269.        
  270.     //编辑器   
  271.     function tinymce($values){   
  272.         if(isset($this->database_options[$values['id']]))   
  273.             $values['std'] = $this->database_options[$values['id']];   
  274.            
  275.         echo '<p>'.$values['name'].'</p>';   
  276.         wp_editor( $values['std'], $values['id'] );   
  277.         //wp_editor( $values['std'], 'content', array('dfw' => true, 'tabfocus_elements' => 'sample-permalink,post-preview', 'editor_height' => 360) );   
  278.         //带配置参数   
  279.         /*wp_editor($meta_box['std'],$meta_box['name'].'_value', $settings = array(quicktags=>0,//取消html模式
  280.         tinymce=>1,//可视化模式  
  281.         media_buttons=>0,//取消媒体上传  
  282.         textarea_rows=>5,//行数设为5  
  283.         editor_class=>"textareastyle") ); */  
  284.     }   
  285.   
  286. }   
  287. ?>  

对应的js文件metabox_fields.js,如果用不到图片上传,可不需要加载js:

  1. jQuery.noConflict();   
  2. jQuery(document).ready(function(){     
  3.     hijack_media_uploader();   
  4.     hijack_preview_pic();   
  5. });   
  6.   
  7. function hijack_preview_pic(){   
  8.     jQuery('.kriesi_preview_pic_input').each(function(){   
  9.         jQuery(this).bind('change focus blur ktrigger', function(){    
  10.             $select = '#' + jQuery(this).attr('name') + '_div';   
  11.             $value = jQuery(this).val();   
  12.             $image = '<img src ="'+$value+'" />';   
  13.             var $image = jQuery($select).html('').append($image).find('img');   
  14.             //set timeout because of safari   
  15.             window.setTimeout(function(){   
  16.                 if(parseInt($image.attr('width')) < 20){       
  17.                     jQuery($select).html('');   
  18.                 }   
  19.             },500);   
  20.         });   
  21.     });   
  22. }   
  23.   
  24. function hijack_media_uploader(){          
  25.         $buttons = jQuery('.k_hijack');   
  26.         $realmediabuttons = jQuery('.media-buttons a');   
  27.         window.custom_editor = false;   
  28.         $buttons.click(function(){     
  29.             window.custom_editor = jQuery(this).attr('id');            
  30.         });   
  31.         $realmediabuttons.click(function(){   
  32.             window.custom_editor = false;   
  33.         });   
  34.         window.original_send_to_editor = window.send_to_editor;   
  35.         window.send_to_editor = function(html){    
  36.             if (custom_editor) {       
  37.                 $img = jQuery(html).attr('src') || jQuery(html).find('img').attr('src') || jQuery(html).attr('href');   
  38.                    
  39.                 jQuery('input[name='+custom_editor+']').val($img).trigger('ktrigger');   
  40.                 custom_editor = false;   
  41.                 window.tb_remove();   
  42.             }else{   
  43.                 window.original_send_to_editor(html);   
  44.             }   
  45.         };   
  46. }   

类文件实例化对应的配置文件metabox.php:

注意

复选框保存的数据为数组

  1. <?php      
  2. //自定义面板类的实例化      
  3. /**********title*************/     
  4. $options = array();      
  5. //page参数为在页面和文章中都添加面板 ,可以添加自定义文章类型   
  6. //context参数为面板在后台的位置,比如side则显示在侧栏      
  7. $boxinfo = array('title' => 'meta box', 'id'=>'ashubox', 'page'=>array('page','post'), 'context'=>'normal', 'priority'=>'low', 'callback'=>'');      
  8.      
  9. $options[] = array"name" => "标题",      
  10.             "type" => "title");      
  11.                   
  12. $options[] = array(      
  13.             "name" => "文本框",      
  14.             "desc" => "",      
  15.             "id" => "ashu_text",      
  16.             "size"=>"40",      
  17.             "std" => "",      
  18.             "type" => "text"     
  19.             );      
  20.                   
  21. $options[] = array(      
  22.             "name" => "文本域",      
  23.             "desc" => "",      
  24.             "id" => "ashu_textarea",      
  25.             "std" => "",      
  26.             "type" => "textarea"     
  27.             );      
  28.                   
  29. $options[] = array(      
  30.             "name" => "图片上传",      
  31.             "desc" => "",      
  32.             "id" => "ashu_upimg",      
  33.             "std" => "",      
  34.             "button_label"=>'上传图片',      
  35.             "type" => "media"     
  36.             );      
  37.                   
  38. $options[] = array(      
  39.             "name" => "单选框",      
  40.             "desc" => "",      
  41.             "id" => "ashu_radio",      
  42.             "std" => 1,      
  43.             "buttons" => array('Yes','No'),   
  44.             "type" => "radio"     
  45.             );      
  46.                   
  47. $options[] = array(      
  48.             "name" => "复选框",      
  49.             "desc" => "喜欢吃啥?",      
  50.             "id" => "ashu_checkbox",      
  51.             "buttons" => array('苹果','香蕉','西瓜','芒果'),   
  52.             "type" => "checkbox"     
  53.             );      
  54.      
  55. $options[] = array(      
  56.             "name" => "下拉选择",      
  57.             "desc" => "",      
  58.             "id" => "ashu_dropdown",      
  59.             "subtype"=> array(      
  60.                 '1'=>'1',      
  61.                 '2'=>'2',      
  62.                 '3'=>'3'      
  63.             ),      
  64.             "type" => "dropdown"     
  65.             );      
  66.                   
  67. $options[] = array(      
  68.             "name" => "选择分类",      
  69.             "desc" => "",      
  70.             "id" => "ashu_cat",      
  71.             "subtype"=> "cat",      
  72.             "type" => "dropdown"     
  73.             );      
  74.                   
  75. $options[] = array(      
  76.             "name" => "选择页面",      
  77.             "desc" => "",      
  78.             "id" => "ashu_page",      
  79.             "subtype"=> "page",      
  80.             "type" => "dropdown"     
  81.             );      
  82.                   
  83. $options[] = array(      
  84.             "name" => "选择菜单",      
  85.             "desc" => "",      
  86.             "id" => "ashu_menu",      
  87.             "subtype"=> "menu",      
  88.             "type" => "dropdown"     
  89.             );      
  90.                   
  91. $options[] = array(      
  92.             "name" => "选择侧边栏",      
  93.             "desc" => "",      
  94.             "id" => "ashu_sidebar",      
  95.             "subtype"=> "sidebar",      
  96.             "type" => "dropdown"     
  97.             );   
  98.   
  99.                   
  100. $options[] = array(      
  101.             "name" => "编辑器",      
  102.             "desc" => "",      
  103.             "id" => "ashu_tinymce",      
  104.             "std" => "",   
  105.             "type" => "tinymce"     
  106.             );                 
  107.                   
  108. $new_box = new ashu_meta_box($options$boxinfo);      
  109. ?>   

使用方法:在主题中加载这两个文件,比如在主题的functions.php中加载两个文件:

  1. include_once('metaboxclass.php');   
  2. include_once('metabox.php');  

则后台文章和页面的编辑页面都会出现配置的自定义面板。

 

字段调用,比如调用上面配置文件中的文本框字段:

  1. $ashu_eitor = get_post_meta($post->ID, "ashu_text", true); //ashu_text为配置文件中文本框的id  

有图有真相,李菊福:

wordpress文章编辑页面添加自定义面板

已有48条评论

阿树工作室进行回复 取消回复