WordPress - 以编程方式添加小部件

时间:2012-04-02 09:33:01

标签: php wordpress-plugin wordpress

我在wordpress.stackexchange.com上问了这个问题,但没有回复。

我想以编程方式将小部件添加到我的wordpress网站。我尝试了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' );

但似乎没有用。我甚至尝试了问题Programmatically add widgets to sidebars中的代码,但无济于事。如果我错过了什么,请告诉我。

三江源

1 个答案:

答案 0 :(得分:3)

我认为你的构造函数错了。请尝试以下方法:

<?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
    }
}

?>

另外,请确保您有一个描述以及所有内容以使其成为插件,并在插件下的管理面板中激活它。