WordPress - add widgets programmatically
I asked this question on wordpress.stackexchange.com but there was no answer.
I want to add widgets to my Wordpress site programmatically. I tried the following code from the codex docs :
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 , to no avail. Please tell me if I am missing something.
Thankyou
+3
source to share
1 answer
I think you have the wrong constructor. 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 everything to make it a plugin and activate it in the admin panel under plugins.
+3
source to share