Wordpress custom widget image upload

前端 未结 2 1799
傲寒
傲寒 2021-01-31 12:03

I\'m busy with building my own Wordpress Widget. Everything works fine except for the Wordpress media up loader. I have created eight buttons and eight input text fields which s

2条回答
  •  旧时难觅i
    2021-01-31 12:24

    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.

    The widget class

    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 '
          
          

    '.esc_html($instance['image_uri']).'

    '; } public function form( $instance ) { // removed the for loop, you can create new instances of the widget instead ?>



    New js file: use the .on() method instead of .click() to attach the event handler.

    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();
      }
    });
    

提交回复
热议问题