Code To Integrate WordPress Media Uploader In Plugin or Theme

By Our Bestseller: WordPress Themes

WordPress media uploader provide an easy way for uploading images, or other graphic files in pages or posts. Therefore many WordPress themes or plugins developer want to integrate WP uploader functionality under theme options panel or plugins.

For that, I came up with this tutorial that make it easy for you to implement such functionality under theme options panel of your WP themes or plugins.

Under the tutorial, I have created a plugin named, WordPress Media Uploader that helps you to upload images.

WP media uploader

1. PHP File – index.php

I have created a new folder named wordpress_media_uploader and stored it under the plugin folder of my WordPress.

(Eg \www\wordpress\my-content\plugins\wordpress_media_uploader)

Now, create a new file named, index.php and save it under wordpress_media_uploader folder.

This file contain code for the following functions-

Create a new plugin and enter its details like plugin name, plugin URI, description, version, author info etc.

Create a main class named, WPMU that encloses following functions-

Function get_instance() – create or return instance of the class.

Function function_construct() used to perform following actions -

Note: Functions called under add_action() defined below.

  • add_action(‘admin_menu’, array(&$this, ‘ink_menu_page’)) – call to a function ink_menu_pageand add its content to the admin menu.
  • add_action(‘admin_enqueue_scripts’, array(&$this, ‘enqueue_admin_js’)) – call to a function enqueue_admin_js and enqueue script to the admin panel.
  • add_action(‘admin_init’, array(&$this, ‘ink_options_setup’)) – add function ink_options_setup on admin initialization.
  • add_action(‘init’, array(&$this, ‘store_in_database’)) – call to a function store_in_database to store value into the database.
  • add_action(‘init’, array(&$this, ‘delete_image’)) – call to a function delete_image to delete the image.
  • add_action(‘admin_enqueue_scripts’, array(&$this, ‘add_stylesheet’)); – call to a function add_stylesheet and add style to admin area.

Function ink_menu_page() – This function add option page under appearance menu and give a call to media_uploader function.

Function media_uploader() – This function consists of page contents like input fields, buttons that you want to display in front end, you will be clear from the below image.

WP media uploader

Function enqueue_admin_js() – This function includes javascript library and one CSS in the admin area. It is compulsory to embed listed built-in scripts like thickbox and media upload.

  • wp_enqueue_script(‘media-upload’) – provides all the functions needed to upload, validate and give format to files
  • wp_enqueue_script(‘thickbox’) - managing the modal window
  • wp_enqueue_style(‘thickbox’) – provides the styles needed for this window
  • wp_enqueue_script(‘script’, plugins_url(‘upload.js’, __FILE__), array(‘jquery’), ”, true) – Initialize the parameters needed to show the window properly. Like plugins_url() – used to specify the URL of the javascript file.

Function add_stylesheet() - This function helps to enqueue stylesheet file, named stylesheet.css

Function ink_options_setup() – This function check working pages are media uploader pages or not and give a call to function replace_window_text.

Function replace_window_text() – This function helps to change the button text of the media uploader launching page. You will be clear from the below image.

upload button

Function store_in_database() – This function help to store image path in the option table of the WordPress database.

Function delete_image() – This function helps to delete the image and its URL from both media library as well as database.

Code


<?php

/*
 Plugin Name: WordPress Media Uploader
 Plugin URI: http://inkthemes.com/
 Description: This plugin is basically focused on uploading images with WordPress Media Uploader. This plugin will guide you on how to integrate WordPress Media Uploader in option panel whether it is of theme or plugin.
 Version: 1.0.0
 Author: InkThemes
 Author URI: http://www.inkthemes.com/
*/

/*
 * We enclose all our functions in a class.
 * Main Class - WPMU stands for WordPress Media Uploader.
*/

Class WPMU {
 /* --------------------------------------------*
 * Attributes
 * -------------------------------------------- */

 /** Refers to a single instance of this class. */

 private static $instance = null;

 /* Saved options */
 public $options;

 /* --------------------------------------------*
 * Constructor
 * -------------------------------------------- */

 /**
 * Creates or returns an instance of this class.
 *
 * @return WPMU_Theme_Options A single instance of this class.
 */
 public static function get_instance() {

 if (null == self::$instance) {
 self::$instance = new self;
 }

 return self::$instance;
 }

// end get_instance;

 /**
 * Initialize the plugin by setting localization, filters, and administration functions.
 */
 private function __construct() {
 // Add the page to the admin menu.
 add_action('admin_menu', array(&$this, 'ink_menu_page'));

 // Register javascript.
 add_action('admin_enqueue_scripts', array(&$this, 'enqueue_admin_js'));

 // Add function on admin initalization.
 add_action('admin_init', array(&$this, 'ink_options_setup'));

 // Call Function to store value into database.
 add_action('init', array(&$this, 'store_in_database'));

 // Call Function to delete image.
 add_action('init', array(&$this, 'delete_image'));

 // Add CSS rule.
 add_action('admin_enqueue_scripts', array(&$this, 'add_stylesheet'));
 }

 /* --------------------------------------------*
 * Functions
 * -------------------------------------------- */

 /**
 * Function will add option page under Appearance Menu.
 */
 public function ink_menu_page() {
 add_theme_page('media_uploader', 'Media Uploader', 'edit_theme_options', 'media_page', array($this, 'media_uploader'));
 }

 //Function that will display the options page.

 public function media_uploader() {
 global $wpdb;
 $img_path = get_option('ink_image');
 ?> 

 <form class="ink_image" method="post" action="#">
 <h2> <b>Upload your Image from here </b></h2>
 <input type="text" name="path" class="image_path" value="<?php echo $img_path; ?>" id="image_path">
 <input type="button" value="Upload Image" class="button-primary" id="upload_image"/> Upload your Image from here.
 <div id="show_upload_preview"> 

 <?php if(! empty($img_path)){
 ?>
 <img src="<?php echo $img_path ; ?>">
 <input type="submit" name="remove" value="Remove Image" class="button-secondary" id="remove_image"/>
 <?php } ?>
 </div>
 <input type="submit" name="submit" class="save_path button-primary" id="submit_button" value="Save Setting">

 </form>
 <?php
 }

//Call three JavaScript library (jquery, media-upload and thickbox) and one CSS for thickbox in the admin head.

 public function enqueue_admin_js() {
 wp_enqueue_script('media-upload'); //Provides all the functions needed to upload, validate and give format to files.
 wp_enqueue_script('thickbox'); //Responsible for managing the modal window.
 wp_enqueue_style('thickbox'); //Provides the styles needed for this window.
 wp_enqueue_script('script', plugins_url('upload.js', __FILE__), array('jquery'), '', true); //It will initialize the parameters needed to show the window properly.
 }

 //Function that will add stylesheet file.
 public function add_stylesheet(){
 wp_enqueue_style( 'stylesheet', plugins_url( 'stylesheet.css', __FILE__ ));
 }

// Here it check the pages that we are working on are the ones used by the Media Uploader.
 public function ink_options_setup() {
 global $pagenow;
 if ('media-upload.php' == $pagenow || 'async-upload.php' == $pagenow) {
 // Now we will replace the 'Insert into Post Button inside Thickbox'
 add_filter('gettext', array($this, 'replace_window_text'), 1, 2);
 // gettext filter and every sentence.
 }
}

/*
 * Referer parameter in our script file is for to know from which page we are launching the Media Uploader as we want to change the text "Insert into Post".
 */
function replace_window_text($translated_text, $text) {
 if ('Insert into Post' == $text) {
 $referer = strpos(wp_get_referer(), 'media_page');
 if ($referer != '') {
 return __('Upload Image', 'ink');
 }
 }
 return $translated_text;
}

// The Function store image path in option table.
public function store_in_database(){
 if(isset($_POST['submit'])){
 $image_path = $_POST['path'];
 update_option('ink_image', $image_path);
 }
}

// Below Function will delete image.
function delete_image() {
 if(isset($_POST['remove'])){
 global $wpdb;
 $img_path = $_POST['path'];

 // We need to get the images meta ID.
 $query = "SELECT ID FROM wp_posts where guid = '" . esc_url($img_path) . "' AND post_type = 'attachment'";
 $results = $wpdb->get_results($query);

 // And delete it
 foreach ( $results as $row ) {
 wp_delete_attachment( $row->ID ); //delete the image and also delete the attachment from the Media Library.
 }
 delete_option('ink_image'); //delete image path from database.
 }
}

}
// End class

WPMU::get_instance();

?>

2. JavaScript File – upload.js

Create a javascript file named, upload.js and save it under wordpress_media_uploader folder.

File contain code for the following-

When user click on upload image button then WordPress media uploader window opens.

On button click event launches a Thickbox function named tb_show() which accepts three parameters in it. Let’s have a look to its parameters one by one.

4

First parameter : name of the window : here it is named as Upload a Image

3

Second parameter : This parameter is divided into sub parameters -

  • WordPress uses a file named media-upload.php to manage window.
  • Media uploader launching page.
  • Type of the file, here it is image. You can also use audio, video, or file etc.
  • TB_iframe : always set this parameter as true, so that window shown in an iframe.
  • post_id : set id as 0 which means image will not be attached to any post.

Third parameter : Set this option as false when you are not going to work with group of images.

send_to_editor – This is an event which deliver image data in HTML format, so that you can put them wherever you want.

tb_remove() – Close the thickbox window automatically after submitting image.

Code


$j = jQuery.noConflict();
$j(document).ready(function() {

/* user clicks button on custom field, runs below code that opens new window */
$j('#upload_image').click(function() {

/*Thickbox function aimed to show the media window. This function accepts three parameters:
*
* Name of the window: "In our case Upload a Image"
* URL : Executes a WordPress library that handles and validates files.
* ImageGroup : As we are not going to work with groups of images but just with one that why we set it false.
*/
tb_show('Upload a Image', 'media-upload.php?referer=media_page&type=image&TB_iframe=true&post_id=0', false);
return false;
});
// window.send_to_editor(html) is how WP would normally handle the received data. It will deliver image data in HTML format, so you can put them wherever you want.

window.send_to_editor = function(html) {
var image_url = $j('img', html).attr('src');
$j('#image_path').val(image_url);
tb_remove(); // calls the tb_remove() of the Thickbox plugin
$j('#submit_button').trigger('click');
}

});

3. CSS File – stylesheet.css

Create a css file named, stylesheet.css and save it under wordpress_media_uploader folder. This file contain code to set the margin and padding of the image and button that appear in front end. Moreover, you can also customize the code according to you.

Code


/*
Created on : Jun 5, 2014, 12:58:19 PM
Author : InkThemes
*/
.ink_image{
margin: 50px 0px 0px 40px;
}

.image_path{
width: 280px;
margin: 20px 10px 20px 0px;
}

#upload_image{
margin: 20px 4px 20px 0px;
}

#show_upload_preview{
margin-bottom: 20px;
}

#remove_image{
margin-left: 15px;

}

Screenshots

1. Go to Dashboard -> Appearance -> Media Uploader and then click on Upload Image button.

screen_1

2. Click on Select Files button.

screen_2

3. Select the image that you want to upload from the folder .

screen_3

4. You can adjust the image size or fill respective fields and then go for final Upload Image option.

screen_4

5. Image is successfully uploaded and appear under your WordPress dashboard.

screen_5

6. You can also check the upload folder of your WordPress which consists of uploaded image in it.

screen_6

Conclusion

I hope above code is clear to you and you can use it correctly to implement its functionality. Moreover, you can customize the code as per your requirement and in case you need any help, free to share in the comment section. I will definitely help you out.

Also share your thoughts about the post and how much you find it helpful to you. I will be glad to know that :)

About Malika Rani
author
I am Malika Rani, a software engineer and a blogger. My hobby is to learn new things, searching exciting and informative discoveries over the web. So blogging is the best platform through which I can share my knowledge and experiences with you. Hope you enjoy reading my blogs and it will be helpful for you.

Comments and Responses

Your email address will not be published. Required fields are marked *