在 wordpress 中创建自定义小部件

我正在尝试为 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' );

您会看到在函数小部件内部我调用了函数 helloWorld(),但是在显示这样的小部件时出现错误


致命错误:在第 38 行调用 /wp-content/plugins/my-widget-plugin/my-widget-plugin.php 中的未定义函数 helloWorld()


为什么我不能在函数内部调用函数?


慕标琳琳
浏览 154回答 1
1回答

慕哥6287543

你忘了添加$this:&nbsp; &nbsp; // Display the widget&nbsp; &nbsp; public function widget( $args, $instance ) {&nbsp; &nbsp; &nbsp; &nbsp; $this->helloWorld();&nbsp; &nbsp; }希望能帮到你。
打开App,查看更多内容
随时随地看视频慕课网APP