【问题标题】:WordPress - Adding widgets programmaticallyWordPress - 以编程方式添加小部件
【发布时间】:2012-04-15 23:16:12
【问题描述】:

我在 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 中的代码,但无济于事。如果我错过了什么,请告诉我。

谢谢

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

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

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

    还要确保你有一个描述和所有这一切使它成为一个插件,并在插件下的管理面板中激活它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多