Skip to content

Instantly share code, notes, and snippets.

@shizhua
Last active April 27, 2017 04:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shizhua/5dcd8de37c8ce98862404b28024546f5 to your computer and use it in GitHub Desktop.
Save shizhua/5dcd8de37c8ce98862404b28024546f5 to your computer and use it in GitHub Desktop.
Frontend Image Uploader in WordPress
( function( $ ) {
$('#upload_form').on('submit', function(e){
e.preventDefault();
var $this = $(this),
nonce = $this.find('#image_upload_nonce').val(),
images_wrap = $('#images_wrap'),
status = $('#status'),
formdata = false;
if ( $this.find('#images').val() == '' ) {
alert('Please select an image to upload');
return;
}
status.fadeIn().text('Loading...')
if (window.FormData) {
formdata = new FormData();
}
var files_data = $('#images');
$.each($(files_data), function(i, obj) {
$.each(obj.files, function(j, file) {
formdata.append('files[' + j + ']', file);
})
});
// our AJAX identifier
formdata.append('action', 'upload_images');
formdata.append('nonce', nonce);
$.ajax({
url: localizedScript.ajaxurl,
type: 'POST',
data: formdata,
dataType: 'json',
processData: false,
contentType: false,
success: function(data) {
if (data.status) {
images_wrap.append(data.message);
status.fadeIn().text('Image uploaded').fadeOut(2000);
} else {
status.fadeIn().text(data.message);
}
}
});
});
} )( jQuery );
<?php
add_action( 'wp_ajax_upload_images', 'upload_images_callback' );
add_action( 'wp_ajax_nopriv_upload_images', 'upload_images_callback' );
if ( ! function_exists( 'upload_images_callback' ) ) :
function upload_images_callback() {
$data = array();
$attachment_ids = array();
if( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'image_upload' ) ){
$files = reArrayFiles($_FILES['files']);
if ( empty($_FILES['files']) ) {
$data['status'] = false;
$data['message'] = __('Please select an image to upload!','twentysixteen');
} elseif ( $files[0]['size'] > 5242880 ) { // Maximum image size is 5M
$data['size'] = $files[0]['size'];
$data['status'] = false;
$data['message'] = __('Image is too large. It must be less than 2M!','twentysixteen');
} else {
$i = 0;
$data['message'] = '';
foreach( $files as $file ){
if( is_array($file) ){
$attachment_id = upload_user_file( $file, false );
if ( is_numeric($attachment_id) ) {
$img_thumb = wp_get_attachment_image_src( $attachment_id, 'thumbnail' );
$data['status'] = true;
$data['message'] .=
'<li id="attachment-'.$attachment_id.'">
<img src="'.$img_thumb[0].'" alt="" />
</li>';
$attachment_ids[] = $attachment_id;
}
}
$i++;
}
if( ! $attachment_ids ){
$data['status'] = false;
$data['message'] = __('An error has occured. Your image was not added.','twentysixteen');
}
}
} else {
$data['status'] = false;
$data['message'] = __('Nonce verify failed','twentysixteen');
}
echo json_encode($data);
die();
}
endif;
<?php
/**
* Template Name: Image Upload
* The template for text ajax image upload
*
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<form name="upload_form" id="upload_form" method="POST" enctype="multipart/form-data">
<input type="file" name="images[]" id="images" accept="image/*" multiple>
<?php wp_nonce_field('image_upload', 'image_upload_nonce');?>
<input type="submit" value="upload">
</form>
<span id="status"></span>
<ul id="images_wrap">
<!-- Images will be added here -->
</ul>
</main><!-- .site-main -->
</div><!-- .content-area -->
<?php get_footer(); ?>
<?php
/**
* Template Name: Image Upload
*
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<!-- Begin the magic -->
<?php if ( isset($_FILES['test_upload']) ) {
$a = $_FILES['test_upload'];
$arr = array();
foreach ($_FILES['test_upload'] as $key => $value) {
foreach ($value as $k => $v) {
$arr[$k][$key] = $a[$key][$k];
}
}
foreach ($arr as $key => $file) {
upload_user_file($file);
}
} ?>
<form id="" class="" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="test_upload[]" id="test_upload" accept="image/*" multiple />
<input type="submit" />
</form>
<!-- End the magic -->
</main><!-- .site-main -->
</div><!-- .content-area -->
<?php get_footer(); ?>
<?php
/**
* Rearray $_FILES array for easy use
*
*/
if ( ! function_exists( 'reArrayFiles' ) ) :
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
endif;
<?php
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment