Example:
<?php
class Image_Fields_Widget extends WP_Widget {
function __construct() {
// Instantiate the parent object
$widget_ops = array(
'classname' => 'widget_image_fields_entries',
'description' => esc_attr__('Image Field Widget - Created by deshisoft', 'eye-theme')
);
$control_ops = array(
'width' => 275
);
parent::__construct( false, 'Image Field Widget', $widget_ops, $control_ops );
}
function widget( $args, $instance ) {
extract( $args );
// Widget output
$title = apply_filters('widget_title', $instance['title']);
$image_url = apply_filters('widget_image_url', $instance['image_url']);
echo $before_widget;
echo '<div style="border:1px solid #ddd; background:#f6f6f6;padding:15px;">';
echo esc_attr($title);
echo '<br/>';
echo esc_attr($image_url);
echo '</div>';
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
// Save widget options
$instance = array();
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['image_url'] = strip_tags( $new_instance['image_url'] );
return $instance;
}
function form( $instance ) {
// Output admin widget options form
$title = $instance['title'];
$image_url = $instance['image_url']; ?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>
<p>Image Uploader</p>
<p><img class="custom_media_image" src="<?php if(!empty($image_url)){echo $image_url;} else { echo bloginfo('template_url').'/inc/no-image.gif';} ?>" style="padding:3px;border:1px solid #ddd;width:97%; display:inline-block" /><input type="text" class="widefat custom_media_url" name="<?php echo $this->get_field_name('image_url'); ?>" id="<?php echo $this->get_field_id('image_url'); ?>" value="<?php echo $image_url; ?>">
<a href="#" class="button custom_media_upload"><?php _e('Upload', THEMENAME); ?></a></p>
<script>
// Image Upload
(function($){
$('.custom_media_upload').click(function() {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
wp.media.editor.send.attachment = function(props, attachment) {
$(button).prev().prev().attr('src', attachment.url);
$(button).prev().val(attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open(button);
return false;
});
})(jQuery);
</script>
<?php
}
}
function image_field_register_widgets() {
register_widget( 'Image_Fields_Widget' );
}
add_action( 'widgets_init', 'image_field_register_widgets' );
?>
Theme Folder -> function.php
Add this line:
require get_template_directory() . '/inc/image_widget.php'; // inc folder name depend on your theme.