简体   繁体   English

在 wordpress 中创建自定义小部件

[英]Creating custom widget in wordpress

I am trying to create a simple plugin widget for wordpress, like this我正在尝试为 wordpress 创建一个简单的插件小部件,就像这样

<?php

// The widget class
class My_Custom_Widget extends WP_Widget {

    // Main constructor
    public function __construct() {
        parent::__construct(
            'my_custom_widget',
            __( 'My Custom Widget', 'text_domain' ),
            array(
                'customize_selective_refresh' => true,
            )
        );
    }

    // The widget form (for the backend )
    public function form( $instance) {}

    // Update widget settings
    public function update($new_instance, $old_instance) {}

    public function helloWorld(){
        echo 'Hello World';
    }

    // Display the widget
    public function widget( $args, $instance ) {
        helloWorld();
    }
}

// Register the widget
function my_register_custom_widget() {
    register_widget( 'My_Custom_Widget' );
}
add_action( 'widgets_init', 'my_register_custom_widget' );

You will see that inside function widget i have call to function helloWorld(), but i got error when displaying widget like this您将看到在 function 小部件内部我调用了 function helloWorld(),但是在显示这样的小部件时出现错误

Fatal error: Call to undefined function helloWorld() in /wp-content/plugins/my-widget-plugin/my-widget-plugin.php on line 38致命错误:在第 38 行的 /wp-content/plugins/my-widget-plugin/my-widget-plugin.php 中调用未定义的 function helloWorld()

Why I can not call function inside function?为什么我不能在 function 里面调用 function?

You forget add $this :您忘记添加$this

    // Display the widget
    public function widget( $args, $instance ) {
        $this->helloWorld();
    }

Hope help you.希望能帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM