WordPress 使用側邊欄小工具,或者其它位置的小工具很是方便,但是默認的那幾個小工具完全不夠用,今天就講解一下如何製作一個小工具,然後接下來的幾篇教程,給出幾個小工具的實例。

今天我們以製作一個按瀏覽量排布的熱門文章小工具。

小工具有三個部分,一、後台顯示,二、數據保存,三、前台顯示。當然如果你的小工具不需要在後台設置什麼數據,那數據保存可以省掉了。一般來講,一個小工具至少應該有這三個部分。

第一步,在自己的主題中新建一個小工具文件,隨便命名,比如我新建一個文件夾 widget 然後在裏面新建一個文件 hotposts.php 。

小工具是一個類,像側邊欄一樣,你還得用代碼註冊它,它在能在後台使用。基本代碼代碼基本上一成不變:

  1. <?php   
  2.   
  3. //定義小工具類 AshuPostViews    
  4. class AshuPostViews extends WP_Widget{   
  5.        
  6.     function AshuPostViews(){   
  7.         //這是定義小工具信息的函數,也是類的構建函數   
  8.     }   
  9.        
  10.     function form($instance){   
  11.         //這是表單函數,也就是控制後台顯示的   
  12.     }   
  13.        
  14.     function update($new_instance,$old_instance){   
  15.         //這是更新數據函數, 小工具如果有設置選項,就需要保存更新數據   
  16.     }   
  17.        
  18.     function widget($args,$instance){   
  19.         //這是控制小工具前台顯示的函數   
  20.     }   
  21.   
  22. }   
  23.   
  24.   
  25. function AshuPostViews(){   
  26.     //註冊小工具   
  27.     register_widget('AshuPostViews');   
  28. }   
  29. //widges_init,小工具初始化的時候執行 AshuPostViews 函數,   
  30. add_action('widgets_init','AshuPostViews');   
  31. ?>  

上面代碼中,三個基本函數 form 、 update 、 widget 函數名是固定的,小工具一般都要有着三個函數,當然小工具還能添加一下自定義的輔助函數。

一、類的構建函數

  1. function AshuPostViews(){   
  2.     $widget_ops = array('classname'=>'widget_postviews','description'=>'按瀏覽量顯示文章');   
  3.     $this->WP_Widget(false,'熱門瀏覽',$widget_ops);   
  4. }  

主要就是配置小工具的基本顯示參數,WP_Widget 函數的參數還能添加其它的。這裏先不做介紹。

二、後台表單函數 form()

這個函數也很簡單,輸出一個表單,誰不會呢?

  1. //參數 $instance 為之前保存過的數據   
  2. function form($instance){   
  3.     //如果之前沒有數據的話,設置兩個默認量   
  4.     $instance = wp_parse_args((array)$instance,array(   
  5.     'title'=>'熱評文章','showPosts'=>10   
  6.     ));   
  7.            
  8.     $title = htmlspecialchars($instance['title']);   
  9.     $showPosts = htmlspecialchars($instance['showPosts']);   
  10.        
  11.     //表格佈局的輸出表單   
  12.     $output = '<table>';   
  13.     $output .= '<tr><td> 標題:</td><td>';   
  14.     $output .= '<input id="'.$this->get_field_id('title') .'" name="'.$this->get_field_name('title').'" type="text" value="'.$instance['title'].'" />';   
  15.     $output .= '</td></tr><tr><td> 文章數量:</td><td>';   
  16.     $output .= '<input id="'.$this->get_field_id('showPosts') .'" name="'.$this->get_field_name('showPosts').'" type="text" value="'.$instance['showPosts'].'" />';   
  17.     $output .= '</td></tr></table>';   
  18.     echo $output;   
  19. }  

只需要處理一下傳入參數,其它的毫無壓力。。圖森破。
三、數據更新函數 update()
這個函數也很簡單,就是根據傳入函數處理一下數據。

  1. //參數 $new_instance 是提交的數據   
  2. function update($new_instance,$old_instance){   
  3.     $instance = $old_instance;   
  4.     //數據處理   
  5.     $instance['title'] = strip_tags(stripslashes($new_instance['title']));   
  6.     $instance['showPosts'] = strip_tags(stripslashes($new_instance['showPosts']));   
  7.     //返回   
  8.     return $instance;   
  9. }  

不解釋了。。
四、前台顯示函數 widget()

  1. //$args 是註冊側邊欄的註冊的幾個變量   
  2. //$instance 是小工具的設置數據   
  3. function widget($args,$instance){   
  4.            
  5.     extract($args); //將數組展開   
  6.     $title = apply_filters('widget_title',emptyempty($instance['title']) ? '&nbsp;' : $instance['title']);   
  7.     $showPosts = emptyempty($instance['showPosts']) ? 10 : $instance['showPosts'];   
  8.        
  9.     echo $before_widget;   
  10.     echo $before_title . $title . $after_title;   
  11.     echo '<ul>';   
  12.         $this->ashu_get_hotpost($showPosts); //使用 ashu_get_hotpost 函數獲取文章   
  13.     echo '</ul>';   
  14.     echo $after_widget;   
  15. }  

這裏的幾個變量 $before_widget 等是在我們註冊側邊欄的時候頂下的,都保存在數組 $args 中,使用 extract 函數可將數組展開為幾個變量。回顧一下注冊側邊欄的時候:

  1. register_sidebar(array(   
  2.     'name'=>'首頁側邊欄',   
  3.     'id'=>'sidebar-1',   
  4.     'before_widget' => '<div id="%1$s" class="widget %2$s">',   
  5.     'after_widget' => '</div>',   
  6.     'before_title' => '<h3>',   
  7.     'after_title' => '</h3>',   
  8.   ));  

有了這幾個基本函數,即可製作一個小工具了,我們還少了一個函數,在 widget 函數中我調用了一個函數 ashu_get_hotpost 來獲取文章,但是這個文章沒有定義,所以我們得添加上這個函數,不然就出錯了。

五:獲取文章函數

  1. //$showposts 參數為顯示文章的數量   
  2. function ashu_get_hotpost($showposts){   
  3.     global $wpdb;   
  4.            
  5.     //使用自定義 sql 查詢語句, 注意, 我的文章瀏覽量是保存在自定義字段 post_views_count 中   
  6.     $result = $wpdb->get_results("SELECT post_id,meta_key,meta_value,ID,post_title FROM $wpdb->postmeta key1 INNER JOIN $wpdb->posts key2 ON key1.post_id = key2.ID where key2.post_type='post' AND key2.post_status='publish' AND key1.meta_key='post_views_count' ORDER BY CAST(key1.meta_value AS SIGNED) DESC LIMIT 0 , $showposts");   
  7.            
  8.     $output = '';   
  9.   
  10.     foreach ($result as $post) {   
  11.         setup_postdata($post);   
  12.         $postid = $post->ID;   
  13.         //計算標題長度   
  14.         if( mb_strlen($post->post_title,"UTF-8")>18 ){   
  15.             $title = strip_tags($post->post_title);   
  16.             $short_title = trim(mb_substr($title ,0,14,"UTF-8"));   
  17.             $short_title .= '...';   
  18.         }else{   
  19.             $short_title = $post->post_title;   
  20.         }   
  21.   
  22.             $output .= '<li class=""><a href="' . get_permalink($postid) . '" title="' . $title .'">' . $short_title .'</a><br /> <span class="">'.$post->meta_value .'Views</span></li>';   
  23.     }     
  24.     echo $output;     
  25. }  

一個完整的按瀏覽量顯示的小工具代碼就只做完成了。。

但是別忘了還有最後一步,,,加載這個小工具文件

在 functions.php 中加入代碼包含這個文件即可,比如我需要加載 widget/hotposts.php:

  1. include_once(TEMPLATEPATH .'/widget/hotposts.php');  

完整代碼

  1. <?php   
  2. /*
  3. Plugin Name: 熱門瀏覽  
  4. Plugin URI:http://www.kutailang.com  
  5. Description: 熱門瀏覽  
  6. Version:1.0  
  7. Author: 樹是我的朋友  
  8. Author URI:http://www.kutailang.com  
  9. */  
  10. //類   
  11. class AshuPostViews extends WP_Widget{   
  12.     function AshuPostViews(){   
  13.         $widget_ops = array('classname'=>'widget_postviews','description'=>'按瀏覽量顯示文章');   
  14.         $this->WP_Widget(false,'熱門瀏覽',$widget_ops);   
  15.     }   
  16.     //表單   
  17.     function form($instance){   
  18.         $instance = wp_parse_args((array)$instance,array(   
  19.         'title'=>'熱評文章','showPosts'=>10   
  20.         ));   
  21.         $title = htmlspecialchars($instance['title']);   
  22.         $showPosts = htmlspecialchars($instance['showPosts']);   
  23.         $output = '<table>';   
  24.         $output .= '<tr><td> 標題:</td><td>';   
  25.         $output .= '<input id="'.$this->get_field_id('title') .'" name="'.$this->get_field_name('title').'" type="text" value="'.$instance['title'].'" />';   
  26.         $output .= '</td></tr><tr><td> 文章數量:</td><td>';   
  27.         $output .= '<input id="'.$this->get_field_id('showPosts') .'" name="'.$this->get_field_name('showPosts').'" type="text" value="'.$instance['showPosts'].'" />';   
  28.         $output .= '</td></tr></table>';   
  29.         echo $output;   
  30.     }   
  31.        
  32.     function update($new_instance,$old_instance){   
  33.         $instance = $old_instance;   
  34.         $instance['title'] = strip_tags(stripslashes($new_instance['title']));   
  35.         $instance['showPosts'] = strip_tags(stripslashes($new_instance['showPosts']));   
  36.         return $instance;   
  37.     }   
  38.        
  39.     function widget($args,$instance){   
  40.         extract($args);   
  41.         $title = apply_filters('widget_title',emptyempty($instance['title']) ? '&nbsp;' : $instance['title']);   
  42.         $showPosts = emptyempty($instance['showPosts']) ? 10 : $instance['showPosts'];   
  43.         echo $before_widget;   
  44.         echo $before_title . $title . $after_title;   
  45.         echo '<ul>';   
  46.             $this->ashu_get_hotpost($showPosts);   
  47.         echo '</ul>';   
  48.         echo $after_widget;   
  49.     }   
  50.     function ashu_get_hotpost($showposts){   
  51.     global $wpdb;      
  52.     $result = $wpdb->get_results("SELECT post_id,meta_key,meta_value,ID,post_title FROM $wpdb->postmeta key1 INNER JOIN $wpdb->posts key2 ON key1.post_id = key2.ID where key2.post_type='post' AND key2.post_status='publish' AND key1.meta_key='post_views_count' ORDER BY CAST(key1.meta_value AS SIGNED) DESC LIMIT 0 , $showposts");   
  53.     $output = '';   
  54.     foreach ($result as $post) {   
  55.   
  56.         $postid = $post->ID;      
  57.         if( mb_strlen($post->post_title,"UTF-8")>18 ){   
  58.             $title = strip_tags($post->post_title);   
  59.             $short_title = trim(mb_substr($title ,0,14,"UTF-8"));   
  60.             $short_title .= '...';   
  61.         }else{   
  62.             $short_title = $post->post_title;   
  63.         }   
  64.   
  65.             $output .= '<li class=""><a href="' . get_permalink($postid) . '" title="' . $title .'">' . $short_title .'</a><br /> <span class="">'.$post->meta_value .'Views</span></li>';   
  66.         $i++;   
  67.     }      
  68.     echo $output;      
  69.     }     
  70. }   
  71.   
  72. function AshuPostViews(){   
  73.     register_widget('AshuPostViews');   
  74. }   
  75. add_action('widgets_init','AshuPostViews');   
  76. ?>