widget create dynamiclly in wordpress plugin

2019-07-18 14:02发布

问题:

I am writing wordpress plugin. This plugin will create widgets based upon response of API call. My API return an array of some third party site links. So based upon count of array, I have to create widgets. Say, response have 10 entries I have to create 10 widgets based upon response. Currently I am creating 10 classes based on response. But I need to iterate through array and create 10 widgets dynamically. Is there any other way I can accomplish this task? please help.

class widget_Mywidget extends WP_Widget {

    function widget_Mywidget() {
     $widget_ops = array( 'classname' => 'widget_Mywidget', 'description' => __( "My Widget" ) );
        $this->WP_Widget('My Widget', __('This is sample Widget'), $widget_ops);    

    }

    function widget($args, $instance) {
        extract($args);

        echo $before_widget;
        echo $before_title;

        if(!empty($instance['title'])) {
            echo $instance['title'];
        } else {
            echo "Sample";
        }

        echo $after_title;

        echo '<script src="www.google.com"></script>';
        echo $after_widget;
    }

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

    function form($instance) {
        //error_check();
        $title = (isset($instance['title'])) ? $instance['title'] : '';

        echo '<div id="myadmin-panel">';

        echo '<label for="' . $this->get_field_id("title") .'">Widget Title:</label>';
        echo '<input type="text" ';
        echo 'name="' . $this->get_field_name("title") . '" ';
        echo 'id="' . $this->get_field_id("title") . '" ';
        echo 'value="' . $title . '" /><br /><br />';
        echo '</div>';

    }
}

回答1:

You could use the old widget interface to register your widgets, but it's deprecated since 2.8, so they might remove it at anytime (plus it will output a warning in WP_DEBUG mode).

The easiest way I know of is using eval() to extend a base class into one that's exactly the same (beware not to use private methods though):

class widget_Mywidget_base extends WP_Widget {
    //Your stuff here
}

for ($i=1;$i<=10;$i++) {
    $widget_class = 'widget_Mywidget_'.$i;
    eval("class $widget_class extends widget_Mywidget_Base { };");
    register_widget( $widget_class );
}