2013-02-15 111 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