Wordpress

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:

class My_Custom_Widget extends WP_Widget { // Widget methods will go here }

2. Define the Constructor (__construct()).

Initialize the widget by setting its name, description, and other parameters that appear in the admin panel.

public function __construct() { parent::__construct( 'my_custom_widget_id', // Base ID of your widget 'My Custom Widget', // Widget name array( 'description' => 'A simple custom widget.' ) // Widget description ); }

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).

public function widget( $args, $instance ) { echo $args['before_widget']; if ( ! empty( $instance['title'] ) ) { echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title']; } // Your custom widget content here echo '

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.

public function form( $instance ) { $title = ! empty( $instance['title'] ) ? $instance['title'] : ''; ?>

}

5. Handle Updates (update()).

This method processes and sanitizes the form input when the widget settings are saved.

public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : ''; return $instance; }

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.

function register_my_custom_widget() { register_widget( 'My_Custom_Widget' ); } add_action( 'widgets_init', 'register_my_custom_widget' );

Leave a Reply

Your email address will not be published. Required fields are marked *