WordPress – Adding widgets programmatically

I asked this question at wordpress.stackexchange.com but no reply.

I want to add widgets to my wordpress site programmatically. I tried the following code from the codex docs:

Read More
class MyNewWidget extends WP_Widget {

    function MyNewWidget() {
        // Instantiate the parent object
        parent::__construct( false, 'My New Widget Title' );
    }

    function widget( $args, $instance ) {
        // Widget output
    }

    function update( $new_instance, $old_instance ) {
        // Save widget options
    }

    function form( $instance ) {
        // Output admin widget options form
    }
}

function myplugin_register_widgets() {
    register_widget( 'MyNewWidget' );
}

add_action( 'widgets_init', 'myplugin_register_widgets' );

But doesn’t seem to work. I even tried the code from the question Programmatically add widgets to sidebars but to no avail. Please tell me if I am missing out something.

Thankyou

Related posts

Leave a Reply

1 comment

  1. I think you have the constructor wrong. Try the following:

    <?php
    
    add_action( 'widgets_init', create_function('', 'return register_widget("MyNewWidget");') );
    
    class MyNewWidget extends WP_Widget {
        function __construct() {
            $widget_ops = array('classname' => 'MyNewWidget', 'description' => __('Widget description'));
            parent::__construct('MyNewWidget', __('Widget Name'), $widget_ops);
        }
    
        function widget( $args, $instance ) {
            extract($args);
            echo $before_widget;
    
            echo $before_title . __('Widget title') . $after_title;
    
            // widget logic/output
    
            echo $after_widget;
        }
    
        function update( $new_instance, $old_instance ) {
            // Save widget options
        }
    
        function form( $instance ) {
            // Output admin widget options form
        }
    }
    
    ?>
    

    Also make sure you have a description and all for this to make it a plugin, and activate it in the admin panel under plugins.