This code extends the WP_Widget base widget class and creates an additional widget that can be used repeatedly:
// Widget class registration
add_action( 'widgets_init', 'my_register_widgets' );
function my_register_widgets() {
register_widget( 'My_Widget' );
}
// Widget class
class My_Widget extends WP_Widget {
function __construct() {
// Start the parent class
parent::__construct(
'widget_identifier', // widget ID, if not specified (leave ''), the ID will be equal to the name of the class in lowercase: my_widget
'Widget name',
array('description' => 'Widget description')
);
// script styles the widget only if it is active
if ( is_active_widget( false, false, $this->id_base ) || is_customize_preview() ) {
add_action('wp_enqueue_scripts', array( $this, 'add_my_widget_scripts' ));
add_action('wp_head', array( $this, 'add_my_widget_style' ) );
}
}
// Widget output
function widget( $args, $instance ){
$title = apply_filters( 'widget_title', $instance['title'] );
echo $args['before_widget'];
if( $title )
echo $args['before_title'] . $title . $args['after_title'];
echo 'Hi!';
echo $args['after_widget'];
}
// Saving widget settings (clearing)
function update( $new_instance, $old_instance ) {
}
// html form of widget settings in the admin panel
function form( $instance ) {
}
// widget script
function add_my_widget_scripts() {
// filter so you can disable scripts
if( ! apply_filters( 'show_my_widget_script', true, $this->id_base ) )
return;
$theme_url = get_stylesheet_directory_uri();
wp_enqueue_script('my_widget_script', $theme_url .'/my_widget_script.js' );
}
// widget styles
function add_my_widget_style() {
// filter so you can disable styles
if( ! apply_filters( 'show_my_widget_style', true, $this->id_base ) )
return;
?>
<style>
.my_widget a{ display:inline; }
</style>
<?php
}
}