0

I'm stuck at the beginning of my custom widget :) When I click the button that should open modal with WP media uploader it doesn't open it. I've enqueued JS for the widget in functions and custom JS loading and show no errors. I also tried to add these buttons to simple metabox and it's working but no result in widget.

Widget PHP

class Deo_Profile_Widget extends WP_Widget {

  // setup the widget name, description etc.
  function __construct() {
    $widget_ops = array(
      'classname'   => "deo_profile_widget",
      'desciption'  => 'Custom Profile Widget',
    );
    parent::__construct( 'deo_profile', 'Deo Profile', $widget_ops);
  }


  // update of the widget
  function update( $new_instance, $old_instance ) {
    $instance = $old_instance;
    return $instance;
  }


  // back-end display of widget
  function form( $instance ) {

    ?>
      <input type="hidden" id="image-hidden-field" name="custom_image_data">
      <input type="button" id="image-upload-button" class="button button-primary" value="Add Image">      
      <input type="button" id="image-delete-button" class="button" value="Remove Image">
    <?php
  }

  // front-end display of widget
  function widget( $args, $instance ) {
    echo "Hey";
  }

}


add_action( 'widgets_init', function() {
  register_widget( 'Deo_Profile_Widget' );
});

Widget JS

(function($){


  /* WordPress Media Uploader
  -------------------------------------------------------*/
  var addButton = $('#image-upload-button');
  var deleteButton = $('#image-delete-button');
  var hiddenField = $('#image-hidden-field');


  var mediaUploader = wp.media.frames.file_frame = wp.media({
    title: 'Select an Image',
    button: {
      text: 'Use This Image'
    },
    multiple: false
  });


  addButton.on('click', function(e) {
    e.preventDefault();
    if ( mediaUploader ) {
      mediaUploader.open();
      return;
    }

  });


})(jQuery);
0

After many hours of testing and exploring I finally found what causing the problem. If I add class to the button it's working. But not any class, only class deo-btn.

So, this will work:

<input type="button" id="image-upload-button" class="deo-btn button button-primary" value="Add Image">

And this is not:

<input type="button" id="image-upload-button" class="button button-primary" value="Add Image">

Also, this will not work:

<input type="button" id="image-upload-button" class="just-button button button-primary" value="Add Image">

What is really weird that I'm still selecting button in JS using ID image-upload-button

| improve this answer | |
  • 1
    removed the rant as there is obviously something wrong with your development setup – Mark Kaplun Jul 13 '17 at 4:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.