Creating custom widget in wordpress

Viewed 527

I am trying to create a simple plugin widget for wordpress, like this

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

Fatal error: Call to undefined function helloWorld() in /wp-content/plugins/my-widget-plugin/my-widget-plugin.php on line 38

Why I can not call function inside function?

1 Answers

You forget add $this:

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

Hope help you.

Related