Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Last active December 27, 2015 10:09
Show Gist options
  • Save wpscholar/7309484 to your computer and use it in GitHub Desktop.
Save wpscholar/7309484 to your computer and use it in GitHub Desktop.
This script handles WordPress image uploads when uploading files using Redactor.js. It uses the 'SHORTINIT' parameter to prevent loading plugins and unnecessary files. NOTE: Images uploaded using this script are NOT imported into the WordPress media library.
<?php
// Make sure required $_FILES values are set before trying to load WordPress
if ( isset( $_FILES['file'] ) ) {
// We don't need all of WordPress, just the basics
define( 'SHORTINIT', true );
// Load WordPress
require( strstr( dirname( __FILE__ ), 'wp-content', true ) . 'wp-load.php' );
// Load additional required files since we did a short init
require( ABSPATH . 'wp-includes/l10n.php' ); // Required to gain access to the __() function
require( ABSPATH . 'wp-includes/formatting.php' ); // Required to gain access to the untrailingslashit() function
require( ABSPATH . 'wp-includes/post.php' ); // Required to gain access to the wp_match_mime_types() function
require( ABSPATH . 'wp-admin/includes/file.php' ); // Required to gain access to the wp_handle_upload() function
// Define WP_CONTENT_URL to avoid PHP notice
if ( ! defined( 'WP_CONTENT_URL' ) ) {
define( 'WP_CONTENT_URL', get_option( 'siteurl' ) . '/wp-content' );
}
/**
* Class Redactor_Image_Upload_For_WordPress
*/
class Redactor_Image_Upload_For_WordPress {
/**
* Handles the upload if a file is available and is of the correct mime type. On success, a JSON object is
* returned to Redactor containing the image URL.
*/
public function __construct ( $file_handle ) {
$url = $this->upload_image();
if ( $url ) {
wp_send_json( array( 'filelink' => $url ) );
}
}
/**
* Upload an image
*
* @param array $file
* @return string The image URL
*/
public function upload_image ( $file ) {
$upload = wp_handle_upload(
$file,
array(
'test_form' => false,
'mimes' => $this->get_image_mime_types(),
)
);
return ! empty( $upload['url'] ) ? $upload['url'] : '';
}
/**
* Get a list of allowable image mime types.
* NOTE: The normal WordPress mime type filter is applied here, so use the 'upload_mimes' filter to customize.
*
* @return array
*/
public function get_image_mime_types () {
$all_mime_types = get_allowed_mime_types();
$mime_type_matches = wp_match_mime_types( 'image', $all_mime_types );
$image_mime_types = array_intersect( $all_mime_types, (array) array_shift( $mime_type_matches ) );
return $image_mime_types;
}
}
// Let our class do all the work
new Redactor_Image_Upload_For_WordPress( 'file' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment