Wordpress Media Uploader in Widget Opening Multiple

The WordPress media library is one of my favourite features in using WordPress over other CMS's, when yous upload a new image into WordPress information technology will convert it to a number of a different sizes. These sizes can exist defined in the settings -> media page, information technology will list three different image types where you can define new sizes for these image types.

These means that every image you lot upload will be converted into 4 dissimilar images, the original image, large, medium and thumbnail sizes, allowing y'all to put a high quality image in whatsoever position of your site.

By default the media library is only bachelor directly from the chief bill of fare of WordPress or from a post edit page. The problem comes when you want to add the this aforementioned functionality into different places such as on a theme options or on the widget admin screen.

In this tutorial we are going to create a widget that has a field to add an image URL with an image you upload directly in the media library. This will as well allow you to select a image from the media library that y'all've previously uploaded.

media-upload

First we first off by creating a new plugin which will be our widget, when the plugin is activated it will register the new widget on the widget_init activeness.

/* * Plugin Name: Media Upload Widget * Plugin URI: http://www.paulund.co.united kingdom * Clarification: A widget that allows you to upload media from a widget * Version: ane.0 * Author: Paul Underwood * Writer URI: http://world wide web.paulund.co.united kingdom * License: GPL2  Copyright 2012  Paul Underwood  This program is free software; you can redistribute it and/or modify it under the terms of the GNU Full general Public License, version 2, as published past the Costless Software Foundation.  This program is distributed in the hope that information technology will exist useful, but WITHOUT Any WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. */ /**  * Register the Widget  */ add_action( 'widgets_init', create_function( '', 'register_widget("pu_media_upload_widget");' ) );

This will search for a class called pu_media_upload_widget and instantiate the class, so we will need to create a new class named pu_media_upload_widget. As nosotros want this to be used every bit a widget you lot as well need to extend the WordPress WP_Widget form, this comes with three methods that you need to override to use the widget.

The methods that you need to override are widget, update and form. The widget method is used to display the widget on the front-end, update method is used to add validation to the values from the admin grade, the class method is the HTML to create the grade in the admin expanse.

When creating a new widget you should try using the Widget boilerplate to become yous started.

class pu_media_upload_widget extends WP_Widget {     /**      * Constructor      **/     public function __construct()     {         $widget_ops = assortment(             'classname' => 'pu_media_upload',             'description' => 'Widget that uses the built in Media library.'         );          parent::__construct( 'pu_media_upload', 'Media Upload Widget', $widget_ops );     }      /**      * Outputs the HTML for this widget.      *      * @param array  An array of standard parameters for widgets in this theme      * @param array  An assortment of settings for this widget instance      * @return void Echoes it'southward output      **/     public function widget( $args, $instance )     {         // Add any html to output the paradigm in the $instance assortment     }      /**      * Deals with the settings when they are saved by the admin. Here is      * where whatsoever validation should be dealt with.      *      * @param array  An array of new settings as submitted past the admin      * @param assortment  An assortment of the previous settings      * @return array The validated and (if necessary) amended settings      **/     public function update( $new_instance, $old_instance )      {      }      /**      * Displays the form for this widget on the Widgets page of the WP Admin area.      *      * @param array  An array of the electric current settings for this widget      * @return void      **/     public part course( $instance )     {             } }

In the constructor of the widget we need to define the settings for WordPress to understand what to do with this widget code, this is washed by calling the parent constructor with settings to annals the widget.

The constructor is also a good place to assign any stylesheets or javascript that we demand to add to the admin expanse to apply the media library. Because we are going to utilize the default WordPress scripts and styles the files we need are already registered with WordPress nosotros but need to enqueue them correctly. The Javascript files we demand to load are media-upload and thickbox, which is the javascript for the pop-upward boxes in the admin surface area. We will too need to make sure that we have loaded the styles for the thickbox dialog boxes.

/**      * Constructor      **/     public function __construct()     {         $widget_ops = array(             'classname' => 'pu_media_upload',             'description' => 'Widget that uses the built in Media library.'         );          parent::__construct( 'pu_media_upload', 'Media Upload Widget', $widget_ops );          add_action('admin_enqueue_scripts', assortment($this, 'upload_scripts'));         add_action('admin_enqueue_styles', array($this, 'upload_styles'));     }      /**      * Upload the Javascripts for the media uploader      */     public role upload_scripts()     {         wp_enqueue_script('media-upload');         wp_enqueue_script('thickbox');         wp_enqueue_script('upload_media_widget', plugin_dir_url(__FILE__) . 'upload-media.js');     }      /**      * Add the styles for the upload media box      */     public function upload_styles()     {         wp_enqueue_style('thickbox');     }

As y'all can run into in the upload_scripts() method we have also defined a Javascript file called upload-media.js. This will be used to tell WordPress what button volition load the media upload box and how to get the paradigm URL dorsum into the Widget textbox to save in the Widget data.

Javascript Code

The following code is what nosotros will add into the upload-media.js file.

Equally y'all tin run across we are going to set a click event on the upload_image_button course, because we need to know what textbox to put the URL of the paradigm in we are going to shop this textbox element in a jQuery data variable.

Then we setup a office to tell WordPress what to do with the prototype data when information technology gets sent back from the media library iframe. This will take the image URL and add this into the textbox value that we stored in the jQuery data variable, and then we will close the media upload window.

The side by side role of this function is the code to display the media upload box on the screen, this will simply open a thickbox dialog with an iframe of the media-upload.php file, which allows the states to upload new images.

jQuery(document).set(function($) {     $(document).on("click", ".upload_image_button", function() {          jQuery.data(document.body, 'prevElement', $(this).prev());          window.send_to_editor = function(html) {             var imgurl = jQuery('img',html).attr('src');             var inputText = jQuery.data(document.body, 'prevElement');              if(inputText != undefined && inputText != '')             {                 inputText.val(imgurl);             }              tb_remove();         };          tb_show('', 'media-upload.php?type=image&TB_iframe=true');         return false;     }); });

The above code will let us to click on our upload button to display a thickbox dialog of the media upload, similar the following image.

media-library

With the Widget setup and the Javascript in place for uploading files we tin add together the HTML in the form() method to actuate the Javascript to upload the images.

All we need for this is a title for the widget, a textbox for the image url and a push button to open the thickbox dialog box. I thing you lot need to think is to add the HTML class of upload_image_button to the push button as this is the selector we assigned the click consequence to open the thickbox.

/**      * Displays the class for this widget on the Widgets page of the WP Admin area.      *      * @param array  An array of the current settings for this widget      * @render void      **/     public function form( $instance )     {         $title = __('Widget Image');         if(isset($instance['title']))         {             $championship = $example['title'];         }          $prototype = '';         if(isset($example['epitome']))         {             $paradigm = $example['image'];         }         ?>         <p>             <label for="<?php echo $this->get_field_name( 'championship' ); ?>"><?php _e( 'Title:' ); ?></label>             <input grade="widefat" id="<?php repeat $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" blazon="text" value="<?php echo esc_attr( $championship ); ?>" />         </p>          <p>             <characterization for="<?php echo $this->get_field_name( 'image' ); ?>"><?php _e( 'Image:' ); ?></label>             <input name="<?php echo $this->get_field_name( 'image' ); ?>" id="<?php echo $this->get_field_id( 'image' ); ?>" grade="widefat" type="text" size="36"  value="<?php echo esc_url( $image ); ?>" />             <input form="upload_image_button button button-primary" type="push" value="Upload Epitome" />         </p>     <?php     }

Now when you click on the upload image button yous should see the media library popular up in an iframe. This is a really adept mode for your users to select or upload images from the widget screen. If you call up you have missed a step below is the full lawmaking for the widget.

Full WordPress Plugin

<?php /* * Plugin Name: Media Upload Widget * Plugin URI: http://world wide web.paulund.co.uk * Description: A widget that allows yous to upload media from a widget * Version: i.0 * Author: Paul Underwood * Writer URI: http://www.paulund.co.uk * License: GPL2  Copyright 2012  Paul Underwood  This program is free software; you can redistribute it and/or modify information technology under the terms of the GNU General Public License, version two, equally published past the Free Software Foundation.  This plan is distributed in the hope that it will exist useful, but WITHOUT Any WARRANTY; without even the unsaid warranty of MERCHANTABILITY or FITNESS FOR A Particular PURPOSE.  See the GNU General Public License for more details. */ /**  * Annals the Widget  */ add_action( 'widgets_init', create_function( '', 'register_widget("pu_media_upload_widget");' ) );  class pu_media_upload_widget extends WP_Widget {     /**      * Constructor      **/     public function __construct()     {         $widget_ops = array(             'classname' => 'pu_media_upload',             'description' => 'Widget that uses the built in Media library.'         );          parent::__construct( 'pu_media_upload', 'Media Upload Widget', $widget_ops );          add_action('admin_enqueue_scripts', array($this, 'upload_scripts'));         add_action('admin_enqueue_styles', array($this, 'upload_styles'));     }      /**      * Upload the Javascripts for the media uploader      */     public function upload_scripts()     {         wp_enqueue_script('media-upload');         wp_enqueue_script('thickbox');         wp_enqueue_script('upload_media_widget', plugin_dir_url(__FILE__) . 'upload-media.js');     }      /**      * Add the styles for the upload media box      */     public function upload_styles()     {         wp_enqueue_style('thickbox');     }      /**      * Outputs the HTML for this widget.      *      * @param array  An array of standard parameters for widgets in this theme      * @param array  An array of settings for this widget instance      * @render void Echoes information technology'southward output      **/     public function widget( $args, $case )     {         // Add together any html to output the prototype in the $example array     }      /**      * Deals with the settings when they are saved by the admin. Here is      * where any validation should be dealt with.      *      * @param array  An array of new settings as submitted by the admin      * @param array  An assortment of the previous settings      * @render array The validated and (if necessary) amended settings      **/     public function update( $new_instance, $old_instance ) {          // update logic goes here         $updated_instance = $new_instance;         return $updated_instance;     }      /**      * Displays the form for this widget on the Widgets page of the WP Admin area.      *      * @param array  An array of the current settings for this widget      * @render void      **/     public function grade( $instance )     {         $championship = __('Widget Image');         if(isset($instance['title']))         {             $title = $instance['title'];         }          $image = '';         if(isset($instance['paradigm']))         {             $paradigm = $case['image'];         }         ?>         <p>             <characterization for="<?php echo $this->get_field_name( 'title' ); ?>"><?php _e( 'Title:' ); ?></characterization>             <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" proper name="<?php repeat $this->get_field_name( 'title' ); ?>" blazon="text" value="<?php repeat esc_attr( $title ); ?>" />         </p>          <p>             <label for="<?php echo $this->get_field_name( 'image' ); ?>"><?php _e( 'Image:' ); ?></label>             <input name="<?php echo $this->get_field_name( 'image' ); ?>" id="<?php repeat $this->get_field_id( 'paradigm' ); ?>" class="widefat" blazon="text" size="36"  value="<?php echo esc_url( $image ); ?>" />             <input class="upload_image_button" type="button" value="Upload Epitome" />         </p>     <?php     } } ?>

baughmansual1946.blogspot.com

Source: https://dzone.com/articles/add-upload-media-library

Related Posts

0 Response to "Wordpress Media Uploader in Widget Opening Multiple"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel