丟了這麼多天沒更新教程了,自己寫到哪裡都快忘了。。
前面幾篇教程演示瞭如何在 WordPress 後臺文章編輯頁面新增自定義面板,今天的這篇文章不能算教程,和 WordPress 後臺教程的結尾一樣,直接放出一個便於使用的類檔案,實際使用的時候只需要包含這個類檔案,然後載入配置檔案即可使用。
使用該類檔案可以建立標題、文字框、文字域、下拉框、核取方塊、圖片即時預覽上傳。不過少了單選框 (radio) 和文字編輯器,因為個人很少用到這兩個,所以就沒加上,如果有需要的,完全可以參照我們前面幾篇教程自己新增上。
說實話,這個類檔案也不完全是我寫的,我也是從一個主題上弄來的,然後修改。
檔案下載 (壓縮包內功四個檔案,分別是類檔案、配置檔案、 js 檔案、 css 檔案)
懶人下載
版本控制
2013.07.08,版本 1.0
- 修改核取方塊功能
- 增加編輯器功能
類檔案metaboxclass.php:
- <?php
- /*
- WordPress 文章自定義欄位類檔案
- Version: 1.0
- Author: 樹是我的朋友
- Author URI: http://www.ashuwp.com
- License: http://www.ashuwp.com/courses/highgrade/298.html
- */
- class ashu_meta_box{
- var $options;
- var $boxinfo;
- //建構函式
- function ashu_meta_box($options,$boxinfo){
- $this->options = $options;
- $this->boxinfo = $boxinfo;
- add_action('admin_menu', array(&$this, 'init_boxes'));
- add_action('save_post', array(&$this, 'save_postdata'));
- }
- //初始化
- function init_boxes(){
- $this->add_script_and_styles();
- $this->create_meta_box();
- }
- //載入 css 和 js 指令碼
- function add_script_and_styles(){
- if(basename( $_SERVER['PHP_SELF']) == "page.php"
- || basename( $_SERVER['PHP_SELF']) == "page-new.php"
- || basename( $_SERVER['PHP_SELF']) == "post-new.php"
- || basename( $_SERVER['PHP_SELF']) == "post.php"
- || basename( $_SERVER['PHP_SELF']) == "media-upload.php")
- {
- //注意載入的指令碼的 url
- wp_enqueue_style('metabox_fields_css', TEMJS_URI. 'metabox_fields.css');
- wp_enqueue_script('metabox_fields_js',TEMJS_URI. 'metabox_fields.js');
- wp_enqueue_style('thickbox');
- wp_enqueue_script('media-upload');
- wp_enqueue_script('thickbox');
- if(isset($_GET['hijack_target']))
- {
- add_action('admin_head', array(&$this,'add_hijack_var'));
- }
- }
- }
- /*************************/
- function add_hijack_var()
- {
- echo "<meta name='hijack_target' content='".$_GET['hijack_target']."' />
"; - }
- //建立自定義面板
- function create_meta_box(){
- if ( function_exists('add_meta_box') && is_array($this->boxinfo['page']) )
- {
- foreach ($this->boxinfo['page'] as $area)
- {
- if ($this->boxinfo['callback'] == '') $this->boxinfo['callback'] = 'new_meta_boxes';
- add_meta_box(
- $this->boxinfo['id'],
- $this->boxinfo['title'],
- array(&$this, $this->boxinfo['callback']),
- $area, $this->boxinfo['context'],
- $this->boxinfo['priority']
- );
- }
- }
- }
- //建立自定義面板的顯示函式
- function new_meta_boxes(){
- global $post;
- //根據型別呼叫顯示函式
- foreach ($this->options as $option)
- {
- if (method_exists($this, $option['type']))
- {
- $meta_box_value = get_post_meta($post->ID, $option['id'], true);
- if($meta_box_value != "") $option['std'] = $meta_box_value;
- echo '<div class="alt kriesi_meta_box_alt meta_box_'.$option['type'].' meta_box_'.$this->boxinfo['context'].'">';
- $this->$option['type']($option);
- echo '</div>';
- }
- }
- //隱藏域
- echo'<input type="hidden" name="'.$this->boxinfo['id'].'_noncename" id="'.$this->boxinfo['id'].'_noncename" value="'.wp_create_nonce( 'ashumetabox' ).'" />';
- }
- //儲存欄位資料
- function save_postdata() {
- if( isset( $_POST['post_type'] ) && in_array($_POST['post_type'],$this->boxinfo['page'] ) && (isset($_POST['save']) || isset($_POST['publish']) ) ){
- $post_id = $_POST['post_ID'];
- foreach ($this->options as $option) {
- if (!wp_verify_nonce($_POST[$this->boxinfo['id'].'_noncename'], 'ashumetabox')) {
- return $post_id ;
- }
- //判斷許可權
- if ( 'page' == $_POST['post_type'] ) {
- if ( !current_user_can( 'edit_page', $post_id ))
- return $post_id ;
- } else {
- if ( !current_user_can( 'edit_post', $post_id ))
- return $post_id ;
- }
- //將預定義字元轉換為 html 實體
- if( $option['type'] == 'tinymce' ){
- $data = stripslashes($_POST[$option['id']]);
- }elseif( $option['type'] == 'checkbox' ){
- $data = $_POST[$option['id']];
- }else{
- $data = htmlspecialchars($_POST[$option['id']], ENT_QUOTES,"UTF-8");
- }
- if(get_post_meta($post_id , $option['id']) == "")
- add_post_meta($post_id , $option['id'], $data, true);
- elseif($data != get_post_meta($post_id , $option['id'], true))
- update_post_meta($post_id , $option['id'], $data);
- elseif($data == "")
- delete_post_meta($post_id , $option['id'], get_post_meta($post_id , $option['id'], true));
- }
- }
- }
- //顯示標題
- function title($values){
- echo '<p>'.$values['name'].'</p>';
- }
- //文字框
- function text($values){
- if(isset($this->database_options[$values['id']])) $values['std'] = $this->database_options[$values['id']];
- echo '<p>'.$values['name'].'</p>';
- echo '<p><input type="text" size="'.$values['size'].'" value="'.$values['std'].'" id="'.$values['id'].'" name="'.$values['id'].'"/>';
- echo $values['desc'].'<br/></p>';
- echo '<br/>';
- }
- //文字域
- function textarea($values){
- if(isset($this->database_options[$values['id']])) $values['std'] = $this->database_options[$values['id']];
- echo '<p>'.$values['name'].'</p>';
- echo '<p><textarea class="kriesi_textarea" cols="60" rows="5" id="'.$values['id'].'" name="'.$values['id'].'">'.$values['std'].'</textarea>';
- echo $values['desc'].'<br/></p>';
- echo '<br/>';
- }
- //媒體上傳
- function media($values){
- if(isset($this->database_options[$values['id']])) $values['std'] = $this->database_options[$values['id']];
- //圖片上傳按鈕
- global $post_ID, $temp_ID;
- $uploading_iframe_ID = (int) (0 == $post_ID ? $temp_ID : $post_ID);
- $media_upload_iframe_src = "media-upload.php?post_id=$uploading_iframe_ID";
- $image_upload_iframe_src = apply_filters('image_upload_iframe_src', "$media_upload_iframe_src&type=image");
- $button = '<a href="'.$image_upload_iframe_src.'&hijack_target='.$values['id'].'&TB_iframe=true" id="'.$values['id'].'" class="k_hijack button thickbox" onclick="return false;" > 上傳</a>';
- //判斷圖片格式, 圖片預覽
- $image = '';
- if($values['std'] != '') {
- $fileextension = substr($values['std'], strrpos($values['std'], '.') + 1);
- $extensions = array('png','gif','jpeg','jpg','pdf','tif');
- if(in_array($fileextension, $extensions))
- {
- $image = '<img src="'.$values['std'].'" />';
- }
- }
- echo '<div id="'.$values['id'].'_div" class="kriesi_preview_pic">'.$image .'</div>';
- echo '<p>'.$values['name'].'</p><p>';
- if($values['desc'] != "") echo '<p>'.$values['desc'].'<br/>';
- echo '<input class="kriesi_preview_pic_input" type="text" size="'.$values['size'].'" value="'.$values['std'].'" name="'.$values['id'].'"/>'.$button;
- echo '</p>';
- echo '<br/>';
- }
- //單選框
- function radio( $values ){
- if(isset($this->database_options[$values['id']]))
- $values['std'] = $this->database_options[$values['id']];
- echo '<p>'.$values['name'].'</p>';
- foreach( $values['buttons'] as $key=>$value ) {
- $checked ="";
- if($values['std'] == $key) {
- $checked = 'checked = "checked"';
- }
- echo '<input '.$checked.' type="radio" class="kcheck" value="'.$key.'" name="'.$values['id'].'"/>'.$value;
- }
- }
- //核取方塊
- function checkbox($values){
- echo '<p>'.$values['name'].'</p>';
- foreach( $values['buttons'] as $key=>$value ) {
- $checked ="";
- if( is_array($values['std']) && in_array($key,$values['std'])) {
- $checked = 'checked = "checked"';
- }
- echo '<input '.$checked.' type="checkbox" class="kcheck" value="'.$key.'" name="'.$values['id'].'[]"/>'.$value;
- }
- echo '<label for="'.$values['id'].'">'.$values['desc'].'</label><br/></p>';
- }
- //下拉框
- function dropdown($values){
- echo '<p>'.$values['name'].'</p>';
- //選擇內容可以使頁面、分類、選單、側邊欄和自定義內容
- if($values['subtype'] == 'page'){
- $select = 'Select page';
- $entries = get_pages('title_li=&orderby=name');
- }else if($values['subtype'] == 'cat'){
- $select = 'Select category';
- $entries = get_categories('title_li=&orderby=name&hide_empty=0');
- }else if($values['subtype'] == 'menu'){
- $select = 'Select Menu in page left';
- $entries = get_terms( 'nav_menu', array( 'hide_empty' => false ) );
- }else if($values['subtype'] == 'sidebar'){
- global $wp_registered_sidebars;
- $select = 'Select a special sidebar';
- $entries = $wp_registered_sidebars;
- }else{
- $select = 'Select...';
- $entries = $values['subtype'];
- }
- echo '<p><select class="postform" id="'. $values['id'] .'" name="'. $values['id'] .'"> ';
- echo '<option value="">'.$select .'</option> ';
- foreach ($entries as $key => $entry){
- if($values['subtype'] == 'page'){
- $id = $entry->ID;
- $title = $entry->post_title;
- }else if($values['subtype'] == 'cat'){
- $id = $entry->term_id;
- $title = $entry->name;
- }else if($values['subtype'] == 'menu'){
- $id = $entry->term_id;
- $title = $entry->name;
- }else if($values['subtype'] == 'sidebar'){
- $id = $entry['id'];
- $title = $entry['name'];
- }else{
- $id = $entry;
- $title = $key;
- }
- if ($values['std'] == $id ){
- $selected = "selected='selected'";
- }else{
- $selected = "";
- }
- echo"<option $selected value='". $id."'>". $title."</option>";
- }
- echo '</select>';
- echo $values['desc'].'<br/></p>';
- echo '<br/>';
- }
- //編輯器
- function tinymce($values){
- if(isset($this->database_options[$values['id']]))
- $values['std'] = $this->database_options[$values['id']];
- echo '<p>'.$values['name'].'</p>';
- wp_editor( $values['std'], $values['id'] );
- //wp_editor( $values['std'], 'content', array('dfw' => true, 'tabfocus_elements' => 'sample-permalink,post-preview', 'editor_height' => 360) );
- //帶配置引數
- /*wp_editor($meta_box['std'],$meta_box['name'].'_value', $settings = array(quicktags=>0,//取消 html 模式
- tinymce=>1,//視覺化模式
- media_buttons=>0,//取消媒體上傳
- textarea_rows=>5,//行數設為 5
- editor_class=>"textareastyle") ); */
- }
- }
- ?>
對應的 js 檔案metabox_fields.js,如果用不到圖片上傳,可不需要載入 js:
- jQuery.noConflict();
- jQuery(document).ready(function(){
- hijack_media_uploader();
- hijack_preview_pic();
- });
- function hijack_preview_pic(){
- jQuery('.kriesi_preview_pic_input').each(function(){
- jQuery(this).bind('change focus blur ktrigger', function(){
- $select = '#' + jQuery(this).attr('name') + '_div';
- $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);
- });
- });
- }
- function hijack_media_uploader(){
- $buttons = jQuery('.k_hijack');
- $realmediabuttons = jQuery('.media-buttons a');
- window.custom_editor = false;
- $buttons.click(function(){
- window.custom_editor = jQuery(this).attr('id');
- });
- $realmediabuttons.click(function(){
- window.custom_editor = false;
- });
- window.original_send_to_editor = window.send_to_editor;
- window.send_to_editor = function(html){
- if (custom_editor) {
- $img = jQuery(html).attr('src') || jQuery(html).find('img').attr('src') || jQuery(html).attr('href');
- jQuery('input[name='+custom_editor+']').val($img).trigger('ktrigger');
- custom_editor = false;
- window.tb_remove();
- }else{
- window.original_send_to_editor(html);
- }
- };
- }
類檔案例項化對應的配置檔案metabox.php:
注意
核取方塊儲存的資料為陣列
- <?php
- //自定義面板類的例項化
- /**********title*************/
- $options = array();
- //page 引數為在頁面和文章中都新增面板 ,可以新增自定義文章型別
- //context 引數為面板在後臺的位置,比如 side 則顯示在側欄
- $boxinfo = array('title' => 'meta box', 'id'=>'ashubox', 'page'=>array('page','post'), 'context'=>'normal', 'priority'=>'low', 'callback'=>'');
- $options[] = array( "name" => "標題",
- "type" => "title");
- $options[] = array(
- "name" => "文字框",
- "desc" => "",
- "id" => "ashu_text",
- "size"=>"40",
- "std" => "",
- "type" => "text"
- );
- $options[] = array(
- "name" => "文字域",
- "desc" => "",
- "id" => "ashu_textarea",
- "std" => "",
- "type" => "textarea"
- );
- $options[] = array(
- "name" => "圖片上傳",
- "desc" => "",
- "id" => "ashu_upimg",
- "std" => "",
- "button_label"=>'上傳圖片',
- "type" => "media"
- );
- $options[] = array(
- "name" => "單選框",
- "desc" => "",
- "id" => "ashu_radio",
- "std" => 1,
- "buttons" => array('Yes','No'),
- "type" => "radio"
- );
- $options[] = array(
- "name" => "核取方塊",
- "desc" => "喜歡吃啥?",
- "id" => "ashu_checkbox",
- "buttons" => array('蘋果','香蕉','西瓜','芒果'),
- "type" => "checkbox"
- );
- $options[] = array(
- "name" => "下拉選擇",
- "desc" => "",
- "id" => "ashu_dropdown",
- "subtype"=> array(
- '1'=>'1',
- '2'=>'2',
- '3'=>'3'
- ),
- "type" => "dropdown"
- );
- $options[] = array(
- "name" => "選擇分類",
- "desc" => "",
- "id" => "ashu_cat",
- "subtype"=> "cat",
- "type" => "dropdown"
- );
- $options[] = array(
- "name" => "選擇頁面",
- "desc" => "",
- "id" => "ashu_page",
- "subtype"=> "page",
- "type" => "dropdown"
- );
- $options[] = array(
- "name" => "選擇選單",
- "desc" => "",
- "id" => "ashu_menu",
- "subtype"=> "menu",
- "type" => "dropdown"
- );
- $options[] = array(
- "name" => "選擇側邊欄",
- "desc" => "",
- "id" => "ashu_sidebar",
- "subtype"=> "sidebar",
- "type" => "dropdown"
- );
- $options[] = array(
- "name" => "編輯器",
- "desc" => "",
- "id" => "ashu_tinymce",
- "std" => "",
- "type" => "tinymce"
- );
- $new_box = new ashu_meta_box($options, $boxinfo);
- ?>
使用方法:在主題中載入這兩個檔案,比如在主題的 functions.php 中載入兩個檔案:
- include_once('metaboxclass.php');
- include_once('metabox.php');
則後臺文章和頁面的編輯頁面都會出現配置的自定義面板。
欄位呼叫,比如呼叫上面配置檔案中的文字框欄位:
- $ashu_eitor = get_post_meta($post->ID, "ashu_text", true); //ashu_text 為配置檔案中文字框的 id
有圖有真相,李菊福:
