Registering custom WordPress widgets

I have created a custom widget in my themes plugin directory and it seems to be working as expected but when I register a second custom widget the 1st one seems to get overridden and I no longer have access to it. Below is my code for the widgets:

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
    }
}

Both widgets have this kind of code structure but with different class names and both widgets have been activated in the plugins section of the WP dashboard. Any help or suggestions would be very much appreciated. Thanks in advance 🙂

Related posts

Leave a Reply

1 comment

  1. You are calling the class WP_Widget with the wrong parameters.

    /**
     * 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() ) {
    

    If you put false (default value) or a string, it’ll work. So, supposing we have a widget Staff and another Stuff, this would do:

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

    Your code is using attribute_escape, which is deprecated. If you enable WP_DEBUG, you’ll see the warning. Anyway, it’s a good practice to develop always with it turned on.
    All this indicates that you are using a bad source as example. This one is the article about custom widgets.