0

I am using wordpress 4.7.2

I am trying to create a simple widget that will only help user to upload an image .

Below my code, when I am selecting an image , it gives me option to insert into post, but I want it not be associated to any post, just want its url and id so that I can use it to display.

I tried to follow use media upload in custom widget and create image uploader widget and wordpress custom widget image uplaaod but could not solved it.

<?php
namespace MyTheme\Widgets;

use \MyTheme\Widgets as Widgets;

class Image extends \WP_Widget {

    public function __construct( $id_base = false, $name = false, $widget_options = array(), $control_options = array() ) {

        $id_base = ( $id_base ) ? $id_base : 'mytheme-widget-image';
        $name = ( $name ) ? $name : __( 'Image', 'mytheme-widget-image-i18n' );

        $widget_options = wp_parse_args( $widget_options, array(
            'classname'   => 'widget_image',
            'description' => __( 'An image from the media library', 'mytheme-widget-image-i18n' )
        ) );

        $control_options = wp_parse_args( $control_options, array( 'width' => 300 ) );

        parent::__construct( $id_base, $name, $widget_options, $control_options );

        add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') );

    }

    public function widget( $args, $instance ) {

        $content = $this->render( $args, $wp_widget );
    }

    public function render( $args, $instance ){
        //generate content
        return $content;
    }

    public function form($instance){

        $widget_img_id = isset($instance['widget_img_id']) ? $instance['widget_img_id'] : '';

        $image_src = isset($instance['widget-img-id']) ? $instance['widget-img-id'] : '';

        $upload_link = esc_url( get_upload_iframe_src( 'image', $widget_img_id ) );

        $is_image = ! empty($image_src);

        ?>
        <div class="widget-img-wrapper">
            <div class="widget-img-container">
                <?php if ( $is_image  ): ?>
                    <img src="<?php echo $image_src; ?>" alt="" style="max-width:100%" />
                <?php endif; ?>
                <p class="hide-if-no-js">
                    <a name="upload_img_src" href="<?php echo $upload_link; ?>" class="upload-widget-img <?php if ( $is_image ){ echo 'hidden'; } ?>">
                         <?php _e('Set custom image') ?>
                    </a>
                    <a class="delete-widget-img <?php if ( ! $is_image  ) { echo 'hidden'; } ?>" 
          href="#">
                        <?php _e('Remove this image') ?>
                    </a>

                    <input class="widget-img-id" name="widget_img_id" type="hidden" value="<?php echo esc_attr( $image_id ); ?>" />
                </p>
            </div>
        </div>
        <?php
    }

    public function update( $new_instance, $old_instance ){

        $instance = array();
        $instance['widget_img_id'] = ( ! empty( $new_instance['widget_img_id'] ) ) ? strip_tags( $new_instance['widget_img_id'] ) : '';

        $instance['upload_img_src'] = ( ! empty( $new_instance['upload_img_src'] ) ) ? strip_tags( $new_instance['upload_img_src'] ) : '';

        return $instance;
    }

    public static function print_footer_js()
    {
        wp_enqueue_media();
        ?>
        <script>
        jQuery(function($){

            // Set all variables to be used in scope
            var frame,
                imageContainer = $('.widget-img-wrapper'), // Your meta box id here
                addImgLink = imageContainer.find('.upload-widget-img'),
                delImgLink = imageContainer.find( '.delete-widget-img'),
                imgContainer = imageContainer.find( '.widget-img-container'),
                imgIdInput = imageContainer.find( '.widget-img-id' );

                // ADD IMAGE LINK
                addImgLink.on( 'click', function( event ){

                    event.preventDefault();

                    // If the media frame already exists, reopen it.
                    if ( frame ) {
                        frame.open();
                        return;
                    }

                    // Create a new media frame
                    frame = wp.media({
                        title: 'Select or Upload Media Of Your Chosen Persuasion',
                        button: {
                            text: 'Use this media'
                        },
                        library: {
                            type: 'image'
                        }
                        multiple: false  // Set to true to allow multiple files to be selected
                    });


                    // When an image is selected in the media frame...
                    frame.on( 'select', function() {

                        // Get media attachment details from the frame state
                        var attachment = frame.state().get('selection').first().toJSON();

                        // Send the attachment URL to our custom image input field.
                        imgContainer.append( '<img src="'+attachment.url+'" alt="" style="max-width:100%;"/>' );

                        // Send the attachment id to our hidden input
                        imgIdInput.val( attachment.id );

                        // Hide the add image link
                        addImgLink.addClass( 'hidden' );

                        // Unhide the remove image link
                        delImgLink.removeClass( 'hidden' );
                    });

                    // Finally, open the modal on click
                    frame.open();
                });

                // DELETE IMAGE LINK
                delImgLink.on( 'click', function( event ){

                    event.preventDefault();

                    // Clear out the preview image
                    imgContainer.html( '' );

                    // Un-hide the add image link
                    addImgLink.removeClass( 'hidden' );

                    // Hide the delete image link
                    delImgLink.addClass( 'hidden' );

                    // Delete the image id from the hidden input
                    imgIdInput.val( '' );

                });

            });
        </script>
        <?php
    }
}
Community
  • 1
  • 1
Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105

2 Answers2

0

I believe, taht "insert into post" is just the default text, and that it doesn't really have anything to do with the post - The file ends up in the media library and in the uploads folders anyway -

function replace_window_text($translated_text, $text) {
    if ('Insert into Post' == $text) {
        $referer = strpos(wp_get_referer(), 'media_page');
        if ($referer != '') {
            return __('Upload Billede', 'ink');
        }
    }
return $translated_text;
}

This is from one of my old projects, where I created a plugin for media uploading. probably doesn't fit your problem, but it can maybe put you on the right path

Stender
  • 2,446
  • 1
  • 14
  • 22
0

The issue with this is add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') ); is unable to enqueue script, neither wp_footer, admin_footer or admin_enqueue_scripts will be able to render script, need to enqueue outside the class. that solves my problem. Do not use this javascript, has problem with instance as used class in js.

<?php
namespace MyTheme\Widgets;

use \MyTheme\Widgets as Widgets;

class Image extends \WP_Widget {

    public function __construct( $id_base = false, $name = false, $widget_options = array(), $control_options = array() ) {

        $id_base = ( $id_base ) ? $id_base : 'mytheme-widget-image';
        $name = ( $name ) ? $name : __( 'Image', 'mytheme-widget-image-i18n' );

        $widget_options = wp_parse_args( $widget_options, array(
            'classname'   => 'widget_image',
            'description' => __( 'An image from the media library', 'mytheme-widget-image-i18n' )
        ) );

        $control_options = wp_parse_args( $control_options, array( 'width' => 300 ) );

        parent::__construct( $id_base, $name, $widget_options, $control_options );

        add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') );

    }

    public function widget( $args, $instance ) {

        $content = $this->render( $args, $wp_widget );
    }

    public function render( $args, $instance ){
        //generate content
        return $content;
    }

    public function form($instance){

        $widget_img_id = isset($instance['widget_img_id']) ? $instance['widget_img_id'] : '';

        $image_src = isset($instance['widget-img-id']) ? $instance['widget-img-id'] : '';

        $upload_link = esc_url( get_upload_iframe_src( 'image', $widget_img_id ) );

        $is_image = ! empty($image_src);

        ?>
        <div class="widget-img-wrapper">
            <div class="widget-img-container">
                <?php if ( $is_image  ): ?>
                    <img src="<?php echo $image_src; ?>" alt="" style="max-width:100%" />
                <?php endif; ?>
                <p class="hide-if-no-js">
                    <a name="upload_img_src" href="<?php echo $upload_link; ?>" class="upload-widget-img <?php if ( $is_image ){ echo 'hidden'; } ?>">
                         <?php _e('Set custom image') ?>
                    </a>
                    <a class="delete-widget-img <?php if ( ! $is_image  ) { echo 'hidden'; } ?>" 
          href="#">
                        <?php _e('Remove this image') ?>
                    </a>

                    <input class="widget-img-id" name="widget_img_id" type="hidden" value="<?php echo esc_attr( $image_id ); ?>" />
                </p>
            </div>
        </div>
        <?php
    }

    public function update( $new_instance, $old_instance ){

        $instance = array();
        $instance['widget_img_id'] = ( ! empty( $new_instance['widget_img_id'] ) ) ? strip_tags( $new_instance['widget_img_id'] ) : '';

        $instance['upload_img_src'] = ( ! empty( $new_instance['upload_img_src'] ) ) ? strip_tags( $new_instance['upload_img_src'] ) : '';

        return $instance;
    }
}

and JS

add_action( 'admin_enqueue_scripts', function(){
   wp_enqueue_media('jquery');
} );

add_action('admin_footer', function(){

   ?>
   <script>
   jQuery(function($){

      // Set all variables to be used in scope
      var frame,
      imageContainer = $('.widget-img-wrapper'), // Your meta box id here
      addImgLink = imageContainer.find('.upload-widget-img'),
      delImgLink = imageContainer.find( '.delete-widget-img'),
      imgContainer = imageContainer.find( '.widget-img-container'),
      imgIdInput = imageContainer.find( '.widget-img-id' );

      // ADD IMAGE LINK
      addImgLink.on( 'click', function( event ){

      event.preventDefault();

      // If the media frame already exists, reopen it.
      if ( frame ) {
          frame.open();
          return;
       }

       // Create a new media frame
       frame = wp.media({
           title: 'Select or Upload Media Of Your Chosen Persuasion',
           button: {
                  text: 'Use this media'
           },
           multiple: false  // Set to true to allow multiple files to be selected
        });


        // When an image is selected in the media frame...
        frame.on( 'select', function() {

            // Get media attachment details from the frame state
            var attachment = frame.state().get('selection').first().toJSON();

           // Send the attachment URL to our custom image input field.
           imgContainer.append( '<img src="'+attachment.url+'" alt="" style="max-width:100%;"/>' );

           // Send the attachment id to our hidden input
           imgIdInput.val( attachment.id );

           // Hide the add image link
           addImgLink.addClass( 'hidden' );

           // Unhide the remove image link
           delImgLink.removeClass( 'hidden' );
        });

        // Finally, open the modal on click
        frame.open();
     });

    // DELETE IMAGE LINK
    delImgLink.on( 'click', function( event ){

    event.preventDefault();

    // Clear out the preview image
    imgContainer.html( '' );

    // Un-hide the add image link
    addImgLink.removeClass( 'hidden' );

    // Hide the delete image link
    delImgLink.addClass( 'hidden' );

    // Delete the image id from the hidden input
    imgIdInput.val( '' );

    });
});
</script>
  <?php
}
Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105