Custom Widget function in Plugin not working?

I took a code straight out of one of my themes I created, and it's a list of all 50 states in an unordered list pac

I took a code straight out of one of my themes I created, and it's a list of all 50 states in an unordered list packed into a widget you can just drag and drop on the sidebar.

The problem is, when I try using this code in a PLUGIN file, I get the following error:

Fatal error: Call to a member function register() on a non-object in C:\xampp\htdocs\wordpress\wp-includes\widgets.php on line 431

Why would it work in the theme, but not in the plugin? By the way, the active theme is NOT the theme I took the code out of.

Here's my code:

Thanks.

I took a code straight out of one of my themes I created, and it's a list of all 50 states in an unordered list packed into a widget you can just drag and drop on the sidebar.

The problem is, when I try using this code in a PLUGIN file, I get the following error:

Fatal error: Call to a member function register() on a non-object in C:\xampp\htdocs\wordpress\wp-includes\widgets.php on line 431

Why would it work in the theme, but not in the plugin? By the way, the active theme is NOT the theme I took the code out of.

Here's my code: http://pastebin/ZeRWW3yb

Thanks.

Share Improve this question asked Feb 24, 2011 at 21:50 JaredJared 3,8453 gold badges35 silver badges58 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 16

try replacing :

register_widget('States_Widget');

with:

add_action('widgets_init', 'register_states_widget');
function register_states_widget() {
    register_widget('States_Widget');
}

Let us assume that you need to initialize a widget inside a class method by passing the widget name as an argument. To accomplish this you would do this:

class WidgetMonster {
    /**
     * Register widget via PHP lambda function as an argument to the add_action function
     * @var $widget_name string | WP_Widget.
     */
    public static function register_widget_helper( $widget_name ) {
        add_action('widgets_init',
            function() use ( &$widget_name ) {
                return register_widget( $widget_name );
            }
        );
    }
}

Note that we need to pass the variable $widget_name name to our lambda function in order to use it. The part doing this is use (&$widget_name). As already noted hooks initialized like this cannot be removed by remove_action.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745212788a4616940.html

相关推荐

  • Custom Widget function in Plugin not working?

    I took a code straight out of one of my themes I created, and it's a list of all 50 states in an unordered list pac

    13小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信