wordpress进阶教程(十):后台创建自定义面板类文件
丢了这么多天没更新教程了,自己写到哪里都快忘了。。
前面几篇教程演示了如何在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
- */
- ashu_meta_box{
- $options;
- $boxinfo;
- //构造函数
- ashu_meta_box($options,$boxinfo){
- $this->options = $options;
- $this->boxinfo = $boxinfo;
- add_action(‘admin_menu’, (&$this, ‘init_boxes’));
- add_action(‘save_post’, (&$this, ‘save_postdata’));
- }
- //初始化
- init_boxes(){
- $this->add_script_and_styles();
- $this->create_meta_box();
- }
- //加载css和js脚本
- add_script_and_styles(){
- (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’);
- (isset($_GET[‘hijack_target’]))
- {
- add_action(‘admin_head’, (&$this,’add_hijack_var’));
- }
- }
- }
- /*************************/
- add_hijack_var()
- {
- echo “<meta name=’hijack_target’ content='”.$_GET[‘hijack_target’].“‘ />n”;
- }
- //创建自定义面板
- create_meta_box(){
- ( function_exists(‘add_meta_box’) && is_array($this->boxinfo[‘page’]) )
- {
- ($this->boxinfo[‘page’] $area)
- {
- ($this->boxinfo[‘callback’] == ”) $this->boxinfo[‘callback’] = ‘new_meta_boxes’;
- add_meta_box(
- $this->boxinfo[‘id’],
- $this->boxinfo[‘title’],
- (&$this, $this->boxinfo[‘callback’]),
- $area, $this->boxinfo[‘context’],
- $this->boxinfo[‘priority’]
- );
- }
- }
- }
- //创建自定义面板的显示函数
- new_meta_boxes(){
- $post;
- //根据类型调用显示函数
- ($this->options $option)
- {
- (method_exists($this, $option[‘type’]))
- {
- $meta_box_value = get_post_meta($post->ID, $option[‘id’], true);
- ($meta_box_value != “”) $option[‘std’] = $meta_box_value;
- echo ‘<div =“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’ ).'” />’;
- }
- //保存字段数据
- save_postdata() {
- ( isset( $_POST[‘post_type’] ) && in_array($_POST[‘post_type’],$this->boxinfo[‘page’] ) && (isset($_POST[‘save’]) || isset($_POST[‘publish’]) ) ){
- $post_id = $_POST[‘post_ID’];
- ($this->options $option) {
- (!wp_verify_nonce($_POST[$this->boxinfo[‘id’].’_noncename’], ‘ashumetabox’)) {
- $post_id ;
- }
- //判断权限
- ( ‘page’ == $_POST[‘post_type’] ) {
- ( !current_user_can( ‘edit_page’, $post_id ))
- $post_id ;
- } {
- ( !current_user_can( ‘edit_post’, $post_id ))
- $post_id ;
- }
- //将预定义字符转换为html实体
- ( $option[‘type’] == ‘tinymce’ ){
- $data = stripslashes($_POST[$option[‘id’]]);
- }( $option[‘type’] == ‘checkbox’ ){
- $data = $_POST[$option[‘id’]];
- }{
- $data = htmlspecialchars($_POST[$option[‘id’]], ENT_QUOTES,“UTF-8”);
- }
- (get_post_meta($post_id , $option[‘id’]) == “”)
- add_post_meta($post_id , $option[‘id’], $data, true);
- ($data != get_post_meta($post_id , $option[‘id’], true))
- update_post_meta($post_id , $option[‘id’], $data);
- ($data == “”)
- delete_post_meta($post_id , $option[‘id’], get_post_meta($post_id , $option[‘id’], true));
- }
- }
- }
- //显示标题
- title($values){
- echo ‘<p>’.$values[‘name’].'</p>’;
- }
- //文本框
- text($values){
- (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/>’;
- }
- //文本域
- textarea($values){
- (isset($this->database_options[$values[‘id’]])) $values[‘std’] = $this->database_options[$values[‘id’]];
- echo ‘<p>’.$values[‘name’].'</p>’;
- echo ‘<p><textarea =“kriesi_textarea” cols=“60” rows=“5” id=“‘.$values[‘id’].'” name=“‘.$values[‘id’].'”>’.$values[‘std’].'</textarea>’;
- echo $values[‘desc’].'<br/></p>’;
- echo ‘<br/>’;
- }
- //媒体上传
- media($values){
- (isset($this->database_options[$values[‘id’]])) $values[‘std’] = $this->database_options[$values[‘id’]];
- //图片上传按钮
- $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’].'” =“k_hijack button thickbox” onclick=“return false;” >上传</a>’;
- //判断图片格式,图片预览
- $image = ”;
- ($values[‘std’] != ”) {
- $fileextension = substr($values[‘std’], strrpos($values[‘std’], ‘.’) + 1);
- $extensions = (‘png’,’gif’,’jpeg’,’jpg’,’pdf’,’tif’);
- (in_array($fileextension, $extensions))
- {
- $image = ‘<img src=“‘.$values[‘std’].'” />’;
- }
- }
- echo ‘<div id=“‘.$values[‘id’].’_div” =“kriesi_preview_pic”>’.$image .'</div>’;
- echo ‘<p>’.$values[‘name’].'</p><p>’;
- ($values[‘desc’] != “”) echo ‘<p>’.$values[‘desc’].'<br/>’;
- echo ‘<input =“kriesi_preview_pic_input” type=“text” size=“‘.$values[‘size’].'” value=“‘.$values[‘std’].'” name=“‘.$values[‘id’].'”/>’.$button;
- echo ‘</p>’;
- echo ‘<br/>’;
- }
- //单选框
- radio( $values ){
- (isset($this->database_options[$values[‘id’]]))
- $values[‘std’] = $this->database_options[$values[‘id’]];
- echo ‘<p>’.$values[‘name’].'</p>’;
- ( $values[‘buttons’] $key=>$value ) {
- $checked =“”;
- ($values[‘std’] == $key) {
- $checked = ‘checked = “checked”‘;
- }
- echo ‘<input ‘.$checked.’ type=“radio” =“kcheck” value=“‘.$key.'” name=“‘.$values[‘id’].'”/>’.$value;
- }
- }
- //复选框
- checkbox($values){
- echo ‘<p>’.$values[‘name’].'</p>’;
- ( $values[‘buttons’] $key=>$value ) {
- $checked =“”;
- ( is_array($values[‘std’]) && in_array($key,$values[‘std’])) {
- $checked = ‘checked = “checked”‘;
- }
- echo ‘<input ‘.$checked.’ type=“checkbox” =“kcheck” value=“‘.$key.'” name=“‘.$values[‘id’].'[]”/>’.$value;
- }
- echo ‘<label =“‘.$values[‘id’].'”>’.$values[‘desc’].'</label><br/></p>’;
- }
- //下拉框
- dropdown($values){
- echo ‘<p>’.$values[‘name’].'</p>’;
- //选择内容可以使页面、分类、菜单、侧边栏和自定义内容
- ($values[‘subtype’] == ‘page’){
- $select = ‘Select page’;
- $entries = get_pages(‘title_li=&orderby=name’);
- } ($values[‘subtype’] == ‘cat’){
- $select = ‘Select category’;
- $entries = get_categories(‘title_li=&orderby=name&hide_empty=0’);
- } ($values[‘subtype’] == ‘menu’){
- $select = ‘Select Menu in page left’;
- $entries = get_terms( ‘nav_menu’, ( ‘hide_empty’ => false ) );
- } ($values[‘subtype’] == ‘sidebar’){
- $wp_registered_sidebars;
- $select = ‘Select a special sidebar’;
- $entries = $wp_registered_sidebars;
- }{
- $select = ‘Select…’;
- $entries = $values[‘subtype’];
- }
- echo ‘<p><select =“postform” id=“‘. $values[‘id’] .'” name=“‘. $values[‘id’] .'”> ‘;
- echo ‘<option value=“”>’.$select .'</option> ‘;
- ($entries $key => $entry){
- ($values[‘subtype’] == ‘page’){
- $id = $entry->ID;
- $title = $entry->post_title;
- } ($values[‘subtype’] == ‘cat’){
- $id = $entry->term_id;
- $title = $entry->name;
- } ($values[‘subtype’] == ‘menu’){
- $id = $entry->term_id;
- $title = $entry->name;
- } ($values[‘subtype’] == ‘sidebar’){
- $id = $entry[‘id’];
- $title = $entry[‘name’];
- }{
- $id = $entry;
- $title = $key;
- }
- ($values[‘std’] == $id ){
- $selected = “selected=’selected'”;
- }{
- $selected = “”;
- }
- echo“<option $selected value='”. $id.“‘>”. $title.“</option>”;
- }
- echo ‘</select>’;
- echo $values[‘desc’].'<br/></p>’;
- echo ‘<br/>’;
- }
- //编辑器
- tinymce($values){
- (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((){
- hijack_media_uploader();
- hijack_preview_pic();
- });
- hijack_preview_pic(){
- jQuery(‘.kriesi_preview_pic_input’).each((){
- jQuery(this).bind(‘change focus blur ktrigger’, (){
- $select = ‘#’ + jQuery(this).attr(‘name’) + ‘_div’;
- $value = jQuery(this).val();
- $image = ‘<img src =“‘+$value+'” />’;
- $image = jQuery($select).html(”).append($image).find(‘img’);
- //set timeout because of safari
- window.setTimeout((){
- (parseInt($image.attr(‘width’)) < 20){
- jQuery($select).html(”);
- }
- },500);
- });
- });
- }
- hijack_media_uploader(){
- $buttons = jQuery(‘.k_hijack’);
- $realmediabuttons = jQuery(‘.media-buttons a’);
- window.custom_editor = false;
- $buttons.click((){
- window.custom_editor = jQuery(this).attr(‘id’);
- });
- $realmediabuttons.click((){
- window.custom_editor = false;
- });
- window.original_send_to_editor = window.send_to_editor;
- window.send_to_editor = (html){
- (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();
- }{
- window.original_send_to_editor(html);
- }
- };
- }
类文件实例化对应的配置文件metabox.php:
注意
复选框保存的数据为数组
- <?php
- //自定义面板类的实例化
- /**********title*************/
- $options = ();
- //page参数为在页面和文章中都添加面板 ,可以添加自定义文章类型
- //context参数为面板在后台的位置,比如side则显示在侧栏
- $boxinfo = (‘title’ => ‘meta box’, ‘id’=>’ashubox’, ‘page’=>(‘page’,’post’), ‘context’=>’normal’, ‘priority’=>’low’, ‘callback’=>”);
- $options[] = ( “name” => “标题”,
- “type” => “title”);
- $options[] = (
- “name” => “文本框”,
- “desc” => “”,
- “id” => “ashu_text”,
- “size”=>“40”,
- “std” => “”,
- “type” => “text”
- );
- $options[] = (
- “name” => “文本域”,
- “desc” => “”,
- “id” => “ashu_textarea”,
- “std” => “”,
- “type” => “textarea”
- );
- $options[] = (
- “name” => “图片上传”,
- “desc” => “”,
- “id” => “ashu_upimg”,
- “std” => “”,
- “button_label”=>’上传图片’,
- “type” => “media”
- );
- $options[] = (
- “name” => “单选框”,
- “desc” => “”,
- “id” => “ashu_radio”,
- “std” => 1,
- “buttons” => (‘Yes’,’No’),
- “type” => “radio”
- );
- $options[] = (
- “name” => “复选框”,
- “desc” => “喜欢吃啥?”,
- “id” => “ashu_checkbox”,
- “buttons” => (‘苹果’,’香蕉’,’西瓜’,’芒果’),
- “type” => “checkbox”
- );
- $options[] = (
- “name” => “下拉选择”,
- “desc” => “”,
- “id” => “ashu_dropdown”,
- “subtype”=> (
- ‘1’=>’1′,
- ‘2’=>’2′,
- ‘3’=>’3′
- ),
- “type” => “dropdown”
- );
- $options[] = (
- “name” => “选择分类”,
- “desc” => “”,
- “id” => “ashu_cat”,
- “subtype”=> “cat”,
- “type” => “dropdown”
- );
- $options[] = (
- “name” => “选择页面”,
- “desc” => “”,
- “id” => “ashu_page”,
- “subtype”=> “page”,
- “type” => “dropdown”
- );
- $options[] = (
- “name” => “选择菜单”,
- “desc” => “”,
- “id” => “ashu_menu”,
- “subtype”=> “menu”,
- “type” => “dropdown”
- );
- $options[] = (
- “name” => “选择侧边栏”,
- “desc” => “”,
- “id” => “ashu_sidebar”,
- “subtype”=> “sidebar”,
- “type” => “dropdown”
- );
- $options[] = (
- “name” => “编辑器”,
- “desc” => “”,
- “id” => “ashu_tinymce”,
- “std” => “”,
- “type” => “tinymce”
- );
- $new_box = ashu_meta_box($options, $boxinfo);
- ?>
使用方法:在主题中加载这两个文件,比如在主题的functions.php中加载两个文件:
- (‘metaboxclass.php’);
- (‘metabox.php’);
则后台文章和页面的编辑页面都会出现配置的自定义面板。
字段调用,比如调用上面配置文件中的文本框字段:
- $ashu_eitor = get_post_meta($post->ID, “ashu_text”, true); //ashu_text为配置文件中文本框的id
有图有真相,李菊福:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END