widget create dynamiclly in wordpress plugin

三世轮回 提交于 2019-12-11 00:10:59

问题


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


来源:https://stackoverflow.com/questions/11226116/widget-create-dynamiclly-in-wordpress-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!