2013-02-15 75 views
2

我在我的主題插件目錄中創建了一個自定義小部件,它似乎按預期工作,但是當我註冊第二個自定義小部件時,第一個似乎被覆蓋,並且我無法再訪問它。下面是我的小部件代碼:註冊自定義WordPress小部件

add_action('widgets_init', create_function('', 'register_widget("staffWidget");') ); 


class staffWidget extends WP_Widget{ 
    function staffWidget() { 
      parent::WP_Widget(true, 'Staff'); 
    } 

    function widget($args, $instance){ 
     echo "test widget"; 
    } 

    function update($new_instance, $old_instance){ 
     return $new_instance; 
    } 

    function form($instance){ 
     $instance = wp_parse_args((array) $instance, array('title' => '')); 
     if($instance['title']){ 
      $title = $instance['title']; 
     } 
     else{ 
      $title = "Add title here"; 
    } 
    ?> 
    <p><label for="<?php echo $this->get_field_id('title'); ?>">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 attribute_escape($title); ?>" /></label></p> 
    <?php 
    } 
} 

兩個窗口有這樣的代碼結構,但不同的類名和兩個小部件已經在WP儀表盤的插件部分被激活。任何幫助或建議將非常感激。在此先感謝:)

回答

1

您正在使用錯誤的參數調用類WP_Widget

/** 
* PHP5 constructor 
* 
* @param string $id_base Optional Base ID for the widget, lower case, 
* if left empty a portion of the widget's class name will be used. Has to be unique. 
* @param string $name Name for the widget displayed on the configuration page. 
* @param array $widget_options Optional Passed to wp_register_sidebar_widget() 
* - description: shown on the configuration page 
* - classname 
* @param array $control_options Optional Passed to wp_register_widget_control() 
* - width: required if more than 250px 
* - height: currently not used but may be needed in the future 
*/ 
function __construct($id_base = false, $name, $widget_options = array(), $control_options = array()) { 

如果你把false(默認值)或string,它會工作。因此,假設我們有一個小窗口的工作人員和其他東西,這會做:

parent::WP_Widget('staff', 'Staff', array(), array()); 

parent::WP_Widget('stuff', 'Stuff', array(), array()); 

你的代碼是使用attribute_escape,它被廢棄了。如果您啓用WP_DEBUG,則會看到警告。無論如何,這是一個很好的習慣,隨着它的開啓始終開發。
所有這些都表明您正在使用不良來源作爲示例。這一個是關於定製小部件的the article

+0

感謝您的幫助,像一個魅力:) – 2013-02-18 10:11:21