IF you want to add custom widget image upload in WordPress? I have simplified the widget a little for this example, removing the for loop as I think you could just create new instances of the widget. This also allows the added benefit of sorting the items. I moved the js to another file as there’s no need to repeat the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | class Home_Rollover_Widget extends WP_Widget { public function __construct() { parent::__construct( 'home-rollover-widget', 'Home Rollover Widget', array( 'description' => 'Home rollover widget' ) ); } public function widget( $args, $instance ) { // basic output just for this example echo '<a href="#"> <img src="'.esc_url($instance['image_uri']).'" /> <h4>'.esc_html($instance['image_uri']).'</h4> </a>'; } public function form( $instance ) { // removed the for loop, you can create new instances of the widget instead ?> <p> <label for="<?php echo $this->get_field_id('text'); ?>">Text</label><br /> <input type="text" name="<?php echo $this->get_field_name('text'); ?>" id="<?php echo $this->get_field_id('text'); ?>" value="<?php echo $instance['text']; ?>" class="widefat" /> </p> <p> <label for="<?php echo $this->get_field_id('image_uri'); ?>">Image</label><br /> <input type="text" class="img" name="<?php echo $this->get_field_name('image_uri'); ?>" id="<?php echo $this->get_field_id('image_uri'); ?>" value="<?php echo $instance['image_uri']; ?>" /> <input type="button" class="select-img" value="Select Image" /> </p> <?php } } // end class // init the widget add_action( 'widgets_init', create_function('', 'return register_widget("Home_Rollover_Widget");') ); // queue up the necessary js function hrw_enqueue() { wp_enqueue_style('thickbox'); wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); // moved the js to an external file, you may want to change the path wp_enqueue_script('hrw', '/wp-content/plugins/home-rollover-widget/script.js', null, null, true); } add_action('admin_enqueue_scripts', 'hrw_enqueue'); |
New js file: use the .on()
method instead of .click()
to attach the event handler.
1 2 3 4 5 6 7 8 9 10 11 12 13 | var image_field; jQuery(function($){ $(document).on('click', 'input.select-img', function(evt){ image_field = $(this).siblings('.img'); tb_show('', 'media-upload.php?type=image&TB_iframe=true'); return false; }); window.send_to_editor = function(html) { imgurl = $('img', html).attr('src'); image_field.val(imgurl); tb_remove(); } }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.