<

Adding the Ability for Users to Upload Images (or other things) to Your Plugin Folder in WordPress

Published on
5,409 Points
2,209 Views
2 Endorsements
Last Modified:
So you have coded your own WordPress plugin and now you want to allow users to upload images to a folder in the plugin folder rather than the default media location? Follow along and this article will show you how to do just that!

Step 1 - PHP File -- index.php



Create a new folder in your plugin folder. For the sake of this example just call it uploaded_images. Next, create a new file named index.php and save it into the newly created folder. Copy the below code into that file:




 

<?php

/*
Plugin Name: (Add a name for your plugin here)
Plugin URI: (Add a link to the plugin here if you want)
Description: (Add a description for your plugin here)
Version: 1.0.0 (This can start with 0.1, 1.0, 1.0.0, however you handle file versions)
Author: (Add your name here)
Author URI: (Add your website address here if you have one)
*/

/*
* Enclose all your functions in a class.
* Main Class - WPIU stands for WordPress Image Uploader.
*/

Class WPIU {
/* --------------------------------------------*
* 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 WPIU_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, 'my_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, 'my_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 image_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('my_image');
?>

<form class="my_image" method="post" action="#">
<h2> <b>Select Where To Upload Your Image From: </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"/>Select where to upload your image from.
<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 the pages we are working with are checked to be sure they are the ones used by the Media Uploader.
public function my_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', 'my');
}
}
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('my_image', $image_path);
}
}

// The Below Function Will Delete The 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('my_image'); //delete image path from database.
}
}

}
// End class

WPIU::get_instance();

?>

                                          

Open in new window




Here is an explanation of all that code so you can customize it to meet your specifications:

This file contains code to complete 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, WPIU 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, ‘my_menu_page’)) – call to a function my_menu_page and 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, ‘my_options_setup’)) – add function my_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 my_menu_page() – This function adds an option page under the appearance menu and calls the media_uploader function.

Function media_uploader() – This function consists of the page contents like input fields, buttons that you want to display in front end, etc.

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

Function wp_enqueue_script(‘media-upload’) – provides all the functions needed to upload, validate and give format to files

Function wp_enqueue_script(‘thickbox’) – manages the modal window wp_enqueue_style (‘thickbox’) – provides the styles needed for this window

Function 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 call the stylesheet file, named stylesheet.css

Function my_options_setup() – This function checks working pages are media uploader pages or not and gives a call to function replace_window_text

Function replace_window_text() – This function helps to change the button text of the media uploader launch page.

Function store_in_database() – This function helps to store the 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 the media library as well as the database.
 

STEP 2 - JavaScript File – upload.js



Create a javascript file named, upload.js and save it under the uploaded_images folder. Put the following code into that file:
 
$j = jQuery.noConflict();
$j(document).ready(function() {

/* user clicks the button on a custom field, runs the below code that opens a 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 : Since we are not going to work with groups of images but rather with just one image is why we set the value to 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');
}

});

                                          

Open in new window


The file contains code for  the following:
 
  • When a user clicks on the Upload Image button, WordPress will open the media uploader window.
  • An On button click event launches the Thickbox function named tb_show() which will accept three different parameters in it.
    • Name of the window
    • This parameter is actually divided into sub parameters –
      • WordPress uses a file named media-upload.php to manage the window.
      • A 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 the image will not be attached to any post.
    • Set this option as false when you are not going to work with group of images.


STEP 3 - CSS File – stylesheet.css



Create a css file named, stylesheet.css and save it under uploaded_images folder.

This file contains the code to set the margin and padding of the image and the button that will appear in front end. Moreover, you can also customize the code according to your needs.
 
/*
Created on : Insert the date you created this file for version purposes.
Author : (Put your name here)
*/
.uploaded_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;

}

                                          

Open in new window


Hope this helps someone out!
2
Comment
Author:Zac Harris
0 Comments

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Join & Write a Comment

Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
The is a quite short video tutorial. In this video, I'm going to show you how to create self-host WordPress blog with free hosting service.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month