WordPress – Extending widget class (adding a widget)
Creating a Custom WordPress Widget by Extending WP_Widget
Extending the WP_Widget class in WordPress is the standard
way to create custom widgets. This involves creating a new PHP class that
inherits from WP_Widget and overrides specific methods to define
the widget's behavior and appearance.
Key Steps:
1. Create a New Class.
Define a new PHP class that extends WP_Widget. For example:
2. Define the Constructor (__construct()).
Initialize the widget by setting its name, description, and other parameters that appear in the admin panel.
3. Define the Frontend Display (widget()).
This method controls what is displayed on the frontend of your website when
the widget is active. It takes $args (widget arguments like
before_widget, after_widget) and
$instance (saved widget settings).
Hello from My Custom Widget!
'; echo $args['after_widget']; }4. Define the Admin Form (form()).
This method creates the form fields that appear in the WordPress admin area, allowing users to customize the widget's settings.
}
5. Handle Updates (update()).
This method processes and sanitizes the form input when the widget settings are saved.
6. Register the Widget.
Finally, register your custom widget using the
register_widget() function, typically hooked into the
widgets_init action in your theme's
functions.php file or a plugin file.