class Image_Widget extends WP_Widget {
// Constructor function
function __construct() {
parent::__construct(
'image_widget',
'Image Widget',
array( 'description' => 'Displays an image' )
);
}
// Widget output function
function widget( $args, $instance ) {
echo $args['before_widget'];
// Check if the image URL is set
if ( ! empty( $instance['image_url'] ) ) {
echo '<img src="' . esc_url( $instance['image_url'] ) . '" />';
}
echo $args['after_widget'];
}
// Widget form function
function form( $instance ) {
$image_url = ! empty( $instance['image_url'] ) ? $instance['image_url'] : '';
?>
<p>
<label for="<?php echo $this->get_field_id( 'image_url' ); ?>">Image URL:</label>
<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'image_url' ); ?>" name="<?php echo $this->get_field_name( 'image_url' ); ?>" value="<?php echo esc_attr( $image_url ); ?>" />
</p>
<?php
}
// Widget update function
function update( $new_instance, $old_instance ) {
$instance = array();
$instance['image_url'] = ! empty( $new_instance['image_url'] ) ? strip_tags( $new_instance['image_url'] ) : '';
return $instance;
}
}
// Register the widget
function register_image_widget() {
register_widget( 'Image_Widget' );
}
add_action( 'widgets_init', 'register_image_widget' );