建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

真香,30天做一套wordpress主题(第6天):侧边栏(wordpress后台制作教程-设置选项类文件)

GG网络技术分享 2025-03-18 16:12 0


真香,30天做一套wordpress主题(第6天):侧边栏

我们将尽量保持文章的循序渐进和通俗易懂,请确保自己已经掌握了那一篇文章的全部内容时才选择跳过,不然可能会错过关键的信息噢~

这里我们假定你已经知晓了以下基础知识,这些基础知识对理解文章内容是至关重要的:

1. HTML/CSS/JS基础

2. PHP基础

3. 如何使用Wordpress

4. 如何搭建web环境

如果你已经知晓了以上基础知识,恭喜你,本系列的任何文章内容对你而言都没有什么难度。

伟大的侧边栏

今天我们开始制作主题的侧边栏(sidebar),wordpress可以把小工具(widgets)放到侧边栏里,我们先为主题开启侧边栏功能,在functions.php里添加如下代码:

function my_sidebar_registration() {

    register_sidebar(array(

        'name' => __( 'Sidebar'),

        'id' => 'sidebar-1',

    ));

}

add_action( 'widgets_init', 'my_sidebar_registration' );

我们就可以后台看到官方默认的一些widgets了,当然,我们还会需要自定义widgets,但是现在,我们先对这些默认widgets提供支持:

看上去有点多,不过没关系,只要把小工具的通用容器设计好了,很多内容都是重复的。我们首先配上一个Categories小工具,然后在首页侧边栏的位置显示出来。

            <aside class="sidebar">

                <?php dynamic_sidebar('my-sidebar'); ?>

            </aside>

这里对于官方的小工具,我们不去动它的DOM结构,只通过CSS进行样式描述就可以了:

还记得我们的my_sidebar_registration吗?我们在里面把一些官方的小工具在我们的主题里去掉,比如image audio video这些,会破坏AMP的规则,其它的暂时没用到的我们也屏蔽了:

    unregister_widget('WP_Widget_Media_Audio');   // remove audio

    unregister_widget('WP_Widget_Media_Video');   // remove video

    unregister_widget('WP_Widget_Media_Image');   // remove image

    unregister_widget('WP_Widget_Media_Gallery');   // remove galley

    unregister_widget('WP_Widget_Calendar');   // remove calendar

    unregister_widget('WP_Nav_Menu_Widget');   // remove nav menu

    unregister_widget('WP_Widget_Pages');   // remove pages menu

    unregister_widget('WP_Widget_RSS');   // remove rss

    unregister_widget('WP_Widget_Text');   // remove text

    unregister_widget('WP_Widget_Tag_Cloud');   // remove tag cloud

鉴于我们需要amp-form保证页面的amp属性,只能把搜索小工具也给移除了,然后我们来手写一个自定义搜索小工具,这里我们为了偷懒直接从wordpress源文件里复制一个WP_Widget_Search修改使用。

第一步,引入amp-form文件(header.php):

<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>

第二步,建立自定义搜索小工具类(functions.php):

class my_search extends WP_Widget {

    public function __construct() {

        $widget_ops = array(

            'classname'                   => 'widget_search',

            'description'                 => __( 'A search form for your site.' ),

            'customize_selective_refresh' => true,

        );

        parent::__construct( 'search', _x( 'Search', 'Search widget' ), $widget_ops );

    }

    public function widget( $args, $instance ) {

        $title = ! empty( $instance['title'] ) ? $instance['title'] : '';

        $title = apply_filters( 'widget_title', $title, $instance, $this->id_base );

        echo $args['before_widget'];

        if ( $title ) {

            echo $args['before_title'] . $title . $args['after_title'];

        }

        echo 

        '<form target="_top" role="search" method="get" class="search-form" action="/">

            <input type="text" class="search-field" placeholder="' . esc_attr_x( 'Search …', 'placeholder' ) . '" value="' . get_search_query() . '" name="s" />

            <button type="submit" class="search-submit"></button>

        </form>';

        echo $args['after_widget'];

    }

    public function form( $instance ) {

        $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );

        $title    = $instance['title'];

        ?>

        <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /></label></p>

        <?php

    }

    public function update( $new_instance, $old_instance ) {

        $instance          = $old_instance;

        $new_instance      = wp_parse_args( (array) $new_instance, array( 'title' => '' ) );

        $instance['title'] = sanitize_text_field( $new_instance['title'] );

        return $instance;

    }

}

这里我们需要知道,__construct构造函数对这个小工具的基本信息进行了描述,form方法定义了后台添加小工具时看到的选项,update方法定义了更新小工具设置时数据的更新,widget方法定义了小工具在前台的展现结构。


第三步,注册这个小工具:

register_widget('my_search');

最后我们就可以在后台使用我们自定义的搜索小工具了,添加后到页面上看看:

这里有一个要特别注意的地方,amp-form对action里的url是有要求的,虽然可以是完整的url也可以是绝对路径,但是最终使用的action url必须是https协议的,否则无法通过amp checker的检测。


总结和预告

今天我们完成了侧边栏的开发,并且创建了属于我们的自定义小工具,通过定义通用css样式,大多数的小工具都直接美化好了,对于不能用的官方小工具,我们先直接屏蔽了

明天我们将稍加休整一下,完成页面的通用底部,实现顶部菜单的二级展开,做一些细节上的优化。

如果你喜欢这个系列的文章,赶快关注我们(数字江湖异志录)吧,不要错过后续的更多干货噢。

wordpress后台制作教程-设置选项类文件

上一篇教程中我们介绍了一个配置wordpress后台选项的类文件构架,这里就将由wp自学笔记整理的类文件源码贴出示众。

版本控制

2013.07.08,版本1.0

  1. 增加数组类型
  2. 修改复选框功能
  3. 添加编辑器功能

懒人下载

  1. <?php   
  2. /*wordpress后台设置类文件
  3. Version: 1.0  
  4. Author: 树是我的朋友  
  5. Author URI: http://www.ashuwp.com  
  6. License:http://www.ashuwp.com/courses/optionpage/214.html  
  7. */  
  8. class ashu_option_class{   
  9.   
  10.     var $options;   
  11.     var $pageinfo;   
  12.     var $database_options;   
  13.     var $saved_optionname;   
  14.        
  15.     //类的构建函数   
  16.     function ashu_option_class($options$pageinfo) {   
  17.         $this->options = $options;   
  18.         $this->pageinfo = $pageinfo;   
  19.         $this->make_data_available(); //准备设置选项数据   
  20.   
  21.         add_action( \'admin_menu\', array(&$this, \'add_admin_menu\') );   
  22.            
  23.         if( isset($_GET[\'page\']) && ($_GET[\'page\'] == $this->pageinfo[\'filename\']) ) {   
  24.             //加载css js   
  25.             add_action(\'admin_init\', array(&$this, \'enqueue_head\'));       
  26.         }   
  27.     }   
  28.        
  29.     function enqueue_head() {   
  30.         //加载的js路径   
  31.         wp_enqueue_script(\'ashu_options_js\', TEMJS_URI.\'ashu_options.js\');    
  32.         wp_enqueue_style(\'ashu_options_css\', TEMJS_URI.\'ashu_options.css\');    
  33.         wp_enqueue_script(\'thickbox\');   
  34.         wp_enqueue_style(\'thickbox\');   
  35.     }   
  36.        
  37.     //创建菜单项函数   
  38.     function add_admin_menu() {   
  39.         //添加顶级菜单项   
  40.         $top_level = \"主题设置\";   
  41.         if(!$this->pageinfo[\'child\']) {   
  42.             add_menu_page($top_level$top_level, \'edit_themes\', $this->pageinfo[\'filename\'], array(&$this, \'initialize\'));   
  43.             define(\'TOP_LEVEL_BASEAME\', $this->pageinfo[\'filename\']);   
  44.         }else{   
  45.             add_submenu_page(TOP_LEVEL_BASEAME, $this->pageinfo[\'full_name\'], $this->pageinfo[\'full_name\'], \'edit_themes\', $this->pageinfo[\'filename\'], array(&$this, \'initialize\'));   
  46.         }   
  47.     }   
  48.        
  49.     function make_data_available() {   
  50.         global $ashu_option//申明全局变量   
  51.            
  52.         foreach ($this->options as $option) {   
  53.             if( isset($option[\'std\']) ) {   
  54.                 $ashu_option_std[$this->pageinfo[\'optionname\']][$option[\'id\']] = $option[\'std\'];   
  55.             }   
  56.         }   
  57.         //选项组名称   
  58.         $this->saved_optionname = \'ashu_\'.$this->pageinfo[\'optionname\'];   
  59.         $ashu_option[$this->pageinfo[\'optionname\']] = get_option($this->saved_optionname);   
  60.            
  61.         //合并数组   
  62.         $ashu_option[$this->pageinfo[\'optionname\']] = array_merge((array)$ashu_option_std[$this->pageinfo[\'optionname\']], (array)$ashu_option[$this->pageinfo[\'optionname\']]);   
  63.            
  64.         //html实体转换   
  65.         $ashu_option[$this->pageinfo[\'optionname\']] = $this->htmlspecialchars_deep($ashu_option[$this->pageinfo[\'optionname\']]);   
  66.        
  67.     }   
  68.        
  69.     //使用递归将预定义html实体转换为字符   
  70.     function htmlspecialchars_deep($mixed$quote_style = ENT_QUOTES, $charset = \'UTF-8\') {   
  71.         if (is_array($mixed) || is_object($mixed)) {   
  72.             foreach($mixed as $key => $value) {   
  73.                 $mixed[$key] = $this->htmlspecialchars_deep($value$quote_style$charset);   
  74.             }   
  75.         }   
  76.         elseif (is_string($mixed)) {   
  77.             $mixed = htmlspecialchars_decode($mixed$quote_style);   
  78.         }   
  79.         return $mixed;   
  80.     }    
  81.        
  82.     function initialize() {   
  83.         $this->get_save_options();   
  84.         $this->display();   
  85.     }   
  86.        
  87.     //显示表单项函数   
  88.     function display() {       
  89.         $saveoption = false;   
  90.         echo \'<div class=\"wrap\">\';   
  91.         echo \'<div class=\"icon32\" id=\"icon-options-general\"><br/></div>\';   
  92.         echo \'<h2>\'.$this->pageinfo[\'full_name\'].\'</h2>\';   
  93.         echo \'<form method=\"post\" action=\"\">\';   
  94.            
  95.         //根据选项类型执行对应函数   
  96.         foreach ($this->options as $option) {   
  97.             if (method_exists($this$option[\'type\'])) {   
  98.                 $this->$option[\'type\']($option);   
  99.                 $saveoption = true;   
  100.             }   
  101.         }   
  102.         if($saveoption) {   
  103.             echo \'<p class=\"submit\">\';   
  104.             echo \'<input type=\"hidden\" value=\"1\" name=\"save_my_options\"/>\';   
  105.             echo \'<input type=\"submit\" name=\"Submit\" class=\"button-primary autowidth\" value=\"Save Changes\" /></p>\';   
  106.         }   
  107.         echo \'</form></div>\';   
  108.     }   
  109.        
  110.     //更新数据   
  111.     function get_save_options() {   
  112.         $options = $newoptions  = get_option($this->saved_optionname);   
  113.         if ( isset( $_POST[\'save_my_options\'] ) ) {   
  114.             echo \'<div class=\"updated fade\" id=\"message\" style=\"\"><p><strong>Settings saved.</strong></p></div>\';   
  115.             $opion_count = 0;   
  116.             foreach ($_POST as $key => $value) {   
  117.                 if( preg_match(\"/^(numbers_)/\"$key$result) ){   
  118.                     $numbers = explode( \',\', $value );   
  119.                     $newoptions[$key] = $numbers;   
  120.                 }elseif( preg_match(\"/^(tinymce_)/\"$key$result) ){   
  121.                     $value = stripslashes($value);   
  122.                     $newoptions[$key] = $value;   
  123.                 }elseif( preg_match(\"/^(checkbox_)/\"$key$result) ){   
  124.                     $newoptions[$key] = $value;   
  125.                 }else{   
  126.                     $value = stripslashes($value);   
  127.                     $newoptions[$key] = htmlspecialchars($value, ENT_QUOTES,\"UTF-8\");   
  128.                 }   
  129.             }   
  130.         }   
  131.                
  132.         if ( $options != $newoptions ) {   
  133.             $options = $newoptions;   
  134.             update_option($this->saved_optionname, $options);   
  135.         }   
  136.            
  137.         if($options) {   
  138.             foreach ($options as $key => $value) {   
  139.                 $options[$key] = empty($options[$key]) ? false : $options[$key];   
  140.             }   
  141.         }   
  142.            
  143.         $this->database_options = $options;   
  144.     }   
  145.        
  146.     /************开头***************/  
  147.     function open($values) {   
  148.         if(!isset($values[\'desc\'])) $values[\'desc\'] = \"\";   
  149.            
  150.         echo \'<table class=\"widefat\">\';   
  151.         echo \'<thead><tr><th colspan=\"2\">\'.$values[\'desc\'].\'&nbsp;</th></tr></thead>\';   
  152.     }   
  153.        
  154.     /***************结尾**************/  
  155.     function close($values) {   
  156.         echo \'<tfoot><tr><th>&nbsp;</th><th>&nbsp;</th></tr></tfoot></table>\';   
  157.     }   
  158.   
  159.     /**********标题***********************/  
  160.     function title($values) {   
  161.         echo \'<h3>\'.$values[\'name\'].\'</h3>\';   
  162.         if (isset($values[\'desc\'])) echo \'<p>\'.$values[\'desc\'].\'</p>\';   
  163.     }   
  164.   
  165.     /*****************************文本域**********************************/  
  166.     function textarea($values) {   
  167.         if(isset($this->database_options[$values[\'id\']]))   
  168.             $values[\'std\'] = $this->database_options[$values[\'id\']];   
  169.   
  170.         echo \'<tr valign=\"top\" >\';   
  171.         echo \'<th scope=\"row\" width=\"200px\">\'.$values[\'name\'].\'</th>\';   
  172.         echo \'<td>\'.$values[\'desc\'].\'<br/>\';   
  173.         echo \'<textarea name=\"\'.$values[\'id\'].\'\" cols=\"60\" rows=\"7\" id=\"\'.$values[\'id\'].\'\" style=\"width: 80%; font-size: 12px;\" class=\"code\">\';   
  174.         echo $values[\'std\'].\'</textarea><br/>\';   
  175.         echo \'<br/></td>\';   
  176.         echo \'</tr>\';   
  177.     }   
  178.        
  179.     /*********************文本框**************************/  
  180.     function text($values) {       
  181.         if(isset($this->database_options[$values[\'id\']])) $values[\'std\'] = $this->database_options[$values[\'id\']];   
  182.            
  183.         echo \'<tr valign=\"top\" >\';   
  184.         echo \'<th scope=\"row\" width=\"200px\">\'.$values[\'name\'].\'</th>\';   
  185.         echo \'<td>\'.$values[\'desc\'].\'<br/>\';   
  186.         echo \'<input type=\"text\" size=\"\'.$values[\'size\'].\'\" value=\"\'.$values[\'std\'].\'\" id=\"\'.$values[\'id\'].\'\" name=\"\'.$values[\'id\'].\'\"/>\';   
  187.         echo \'<br/><br/></td>\';   
  188.         echo \'</tr>\';   
  189.     }   
  190.        
  191.   
  192.     /**************复选框*******************/  
  193.     function checkbox($values) {   
  194.         if(isset($this->database_options[$values[\'id\']])) $values[\'std\'] = $this->database_options[$values[\'id\']];   
  195.            
  196.         echo \'<tr valign=\"top\">\';   
  197.         echo \'<th scope=\"row\" width=\"200px\">\'.$values[\'name\'].\'</th>\';   
  198.         echo \'<td>\'.$values[\'desc\'].\'<br/>\';   
  199.            
  200.         foreach$values[\'buttons\'] as $key=>$value ) {   
  201.             $checked =\"\";   
  202.             ifis_array($values[\'std\']) && in_array($key,$values[\'std\'])) {   
  203.                 $checked = \'checked = \"checked\"\';   
  204.             }   
  205.             echo \'<input \'.$checked.\' type=\"checkbox\" class=\"kcheck\" value=\"\'.$key.\'\" name=\"\'.$values[\'id\'].\'[]\"/>\'.$value;   
  206.         }   
  207.   
  208.            
  209.         echo \'<label for=\"\'.$values[\'id\'].\'\">\'.$values[\'desc\'].\'</label><br/>\';   
  210.         echo \'<br/></td>\';   
  211.         echo \'</tr>\';   
  212.     }   
  213.   
  214.     /**********************单选框******************************/  
  215.     function radio($values) {   
  216.         if(isset($this->database_options[$values[\'id\']])) $values[\'std\'] = $this->database_options[$values[\'id\']];   
  217.            
  218.         echo \'<tr valign=\"top\" >\';   
  219.         echo \'<th scope=\"row\" width=\"200px\">\'.$values[\'name\'].\'</th>\';   
  220.         echo \'<td>\'.$values[\'desc\'].\'<br/>\';   
  221.            
  222.         foreach($values[\'buttons\'] as $key=>$value) {      
  223.             $checked =\"\";   
  224.             if(isset($values[\'std\']) && ($values[\'std\'] == $key)) {   
  225.                 $checked = \'checked = \"checked\"\';   
  226.             }   
  227.            
  228.             echo \'<p><input \'.$checked.\' type=\"radio\" class=\"kcheck\" value=\"\'.$key.\'\" name=\"\'.$values[\'id\'].\'\"/>\';   
  229.             echo \'<label for=\"\'.$values[\'id\'].\'\">\'.$value.\'</label></p>\';   
  230.         }   
  231.            
  232.         echo \'<br/></td>\';   
  233.         echo \'</tr>\';   
  234.     }   
  235.     /*****************数组***********************/  
  236.     function numbers_array($values){   
  237.         if(isset($this->database_options[$values[\'id\']]))   
  238.             $values[\'std\'] = $this->database_options[$values[\'id\']];   
  239.         else  
  240.             $values[\'std\']=array();   
  241.   
  242.         $nums = implode( \',\', $values[\'std\'] );   
  243.            
  244.         echo \'<tr valign=\"top\" >\';   
  245.         echo \'<th scope=\"row\" width=\"200px\">\'.$values[\'name\'].\'</th>\';   
  246.         echo \'<td>\'.$values[\'desc\'].\'<br/>\';   
  247.         echo \'<input type=\"text\" size=\"\'.$values[\'size\'].\'\" value=\"\'.$nums.\'\" id=\"\'.$values[\'id\'].\'\" name=\"\'.$values[\'id\'].\'\"/>\';   
  248.         echo \'<br/><br/></td>\';   
  249.         echo \'</tr>\';   
  250.     }   
  251.   
  252.     /********************下拉框*********************/  
  253.     function dropdown($values) {       
  254.         if(!isset($this->database_options[$values[\'id\']]) && isset($values[\'std\'])) $this->database_options[$values[\'id\']] = $values[\'std\'];   
  255.                    
  256.         echo \'<tr valign=\"top\" >\';   
  257.         echo \'<th scope=\"row\" width=\"200px\">\'.$values[\'name\'].\'</th>\';   
  258.         echo \'<td>\'.$values[\'desc\'].\'<br/>\';   
  259.            
  260.             if($values[\'subtype\'] == \'page\') {   
  261.                 $select = \'Select page\';   
  262.                 $entries = get_pages(\'title_li=&orderby=name\');   
  263.             }else if($values[\'subtype\'] == \'sidebar\'){   
  264.                 global $wp_registered_sidebars;   
  265.                 $select = \'Select a special sidebar\';   
  266.                 $entries = $wp_registered_sidebars;   
  267.             }else if($values[\'subtype\'] == \'cat\'){   
  268.                 $select = \'Select category\';   
  269.                 $entries = get_categories(\'title_li=&orderby=name&hide_empty=0\');   
  270.             }   
  271.             else  
  272.             {      
  273.                 $select = \'Select...\';   
  274.                 $entries = $values[\'subtype\'];   
  275.             }   
  276.            
  277.             echo \'<select class=\"postform\" id=\"\'. $values[\'id\'] .\'\" name=\"\'. $values[\'id\'] .\'\"> \';   
  278.             echo \'<option value=\"\">\'.$select .\'</option>  \';   
  279.   
  280.             foreach ($entries as $key => $entry) {   
  281.                 if($values[\'subtype\'] == \'page\')   
  282.                 {   
  283.                     $id = $entry->ID;   
  284.                     $title = $entry->post_title;   
  285.                 }else if($values[\'subtype\'] == \'cat\'){   
  286.                     $id = $entry->term_id;   
  287.                     $title = $entry->name;   
  288.                 }else if($values[\'subtype\'] == \'sidebar\'){   
  289.                     $id = $entry[\'id\'];   
  290.                     $title = $entry[\'name\'];   
  291.                 }   
  292.                 else  
  293.                 {   
  294.                     $id = $key;    
  295.                     $title = $entry;           
  296.                 }   
  297.   
  298.                 if ($this->database_options[$values[\'id\']] == $id )   
  299.                 {   
  300.                     $selected = \"selected=\'selected\'\";     
  301.                 }   
  302.                 else  
  303.                 {   
  304.                     $selected = \"\";        
  305.                 }   
  306.                    
  307.                 echo\"<option $selected value=\'\"$id.\"\'>\"$title.\"</option>\";   
  308.             }   
  309.            
  310.         echo \'</select>\';   
  311.             
  312.         echo \'<br/><br/></td>\';   
  313.         echo \'</tr>\';   
  314.     }   
  315.        
  316.     /*******************上传*****************************/  
  317.     function upload($values) {     
  318.         $prevImg = \'\';   
  319.         if(isset($this->database_options[$values[\'id\']])) $values[\'std\'] = $this->database_options[$values[\'id\']];   
  320.         if($values[\'std\'] != \'\'){$prevImg = \'<img src=\'.$values[\'std\'].\' alt=\"\" />\';}   
  321.            
  322.         echo \'<tr valign=\"top\" >\';   
  323.         echo \'<th scope=\"row\" width=\"200px\">\'.$values[\'name\'].\'</th>\';   
  324.         echo \'<td>\';   
  325.         echo \'<div class=\"preview_pic_optionspage\" id=\"\'.$values[\'id\'].\'_div\">\'.$prevImg.\'</div>\';   
  326.         echo $values[\'desc\'].\'<br/>\';   
  327.         echo \'<input type=\"text\" size=\"60\" value=\"\'.$values[\'std\'].\'\" name=\"\'.$values[\'id\'].\'\" class=\"upload_pic_input\" />\';   
  328.         echo \'&nbsp;<a onclick=\"return false;\" title=\"\" class=\"k_hijack button thickbox\" id=\"\'.$values[\'id\'].\'\" href=\"media-upload.php?type=image&amp;hijack_target=\'.$values[\'id\'].\'&amp;TB_iframe=true\">Insert Image</a>\';   
  329.            
  330.         echo \'<br/><br/></td>\';   
  331.         echo \'</tr>\';   
  332.     }   
  333.     //编辑器   
  334.     function tinymce($values){   
  335.         if(isset($this->database_options[$values[\'id\']]))   
  336.             $values[\'std\'] = $this->database_options[$values[\'id\']];   
  337.                
  338.         echo \'<tr valign=\"top\" >\';   
  339.         echo \'<th scope=\"row\" width=\"200px\">\'.$values[\'name\'].\'</th>\';   
  340.         echo \'<td>\'.$values[\'desc\'].\'<br/>\';   
  341.         wp_editor( $values[\'std\'], $values[\'id\'],$settings=array(\'tinymce\'=>1,\'media_buttons\'=>0,) );   
  342.         echo \'<br/></td>\';   
  343.         echo \'</tr>\';   
  344.     }   
  345.   
  346. }   
  347. ?>  

标签:

提交需求或反馈

Demand feedback