php - Creating custom widget in wordpress

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?
Answer
Solution:
You forget add$this
:
// Display the widget
public function widget( $args, $instance ) {
$this->helloWorld();
}
Hope help you.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: object not found by the @paramconverter annotation.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.