Upload media in frontend

DOMJSPHP
<form class="uk-margin" action="" method="post">
  <div class="uk-margin" uk-form-custom style="width:100%;">
    <input type="file" class="btnUpload" id="user_brand_banner" accept="image/*" style="opacity: 0" />
    <button class="uk-position-relative uk-border-rounded link-opacity" style="background-color: #F3F1F3; width: 100%; height: 300px; border: 2px dashed #ccc;">
      <div class="uk-position-center uk-text-center text-height text-default"><i uk-icon="icon:cloud-upload;ratio:3"> </i><br>點擊上傳你的作者頁Banner</div>
      <div class="uk-background-cover uk-position-top-left" id="imgBannerPreview" data-src="<?php echo get_field('user_brand_banner','user_'.wp_get_current_user()->ID); ?>" uk-img style="width: 100%; height: 100%;"></div>
    </button>
    <p class="uk-margin-small-top uk-text-center">尺寸建議:1200 x 300px,檔案大小不得大於 300kb</p>
  </div>
</form>
var $ = jQuery.noConflict();
 
  $('.btnUpload').on('change', prepareUpload);

  function prepareUpload(event) { 
    var file = event.target.files;
    var id = $(this).attr('id');
    var security = $('#security').val();
    var data = new FormData();
    data.append("action", "upload_image");
    data.append("security", security);
    if( id === 'user_brand_banner'){
      $.each(file, function(key, value){
        data.append("user_brand_banner", value);
      })
    } else {
      $.each(file, function(key, value){
        data.append("user_brand_logo", value);
      })
    }

    $.ajax({
      url: '<?php echo admin_url("admin-ajax.php");  ?>',
      type: 'POST',
      data: data,
      cache: false,
      dataType: 'json',
      processData: false, // Don't process the files
      contentType: false, // Set content type to false as jQuery will tell the server its a query string request
      success: function(data, textStatus, jqXHR) {	
        if( data.response == "SUCCESS" ){
          var preview = "";
          if( data.type === "image/jpg" 
            || data.type === "image/png" 
            || data.type === "image/gif"
            || data.type === "image/jpeg"
          ) {
            if( id === 'user_brand_banner'){
              $('#imgBannerPreview').attr('data-src',data.url);
            } else {
              $('#imgLogoPreview').attr('data-src',data.url);
            }
          } else {
            preview = data.filename;
          }
        } else {
            alert( data.error );
        }
    }

    });

  }
add_action('wp_ajax_upload_image', 'upload_handle' );

function upload_handle() {

	$nonce = $_POST['security'];
  if (!wp_verify_nonce($nonce, 'ajax-upload-nonce')) { 
		wp_send_json_error(array('code' => 500, 'data' => '', 'msg' => '錯誤的請求'));
	}

  $current_user = wp_get_current_user();
	$usingUploader = 2;
	$fileErrors = array(
		0 => "There is no error, the file uploaded with success",
		1 => "The uploaded file exceeds the upload_max_files in server settings",
		2 => "The uploaded file exceeds the MAX_FILE_SIZE from html form",
		3 => "The uploaded file uploaded only partially",
		4 => "No file was uploaded",
		6 => "Missing a temporary folder",
		7 => "Failed to write file to disk",
		8 => "A PHP extension stoped file to upload" );
	$posted_data =  isset( $_POST ) ? $_POST : array();
	$file_data = isset( $_FILES ) ? $_FILES : array();
	$data = array_merge( $posted_data, $file_data );
	$response = array();
	if( $usingUploader == 1 ) {
		if(isset($data['user_brand_banner'])){
			$uploaded_file = wp_handle_upload( $data['user_brand_banner'], array( 'test_form' => false ) );
		} else {
			$uploaded_file = wp_handle_upload( $data['user_brand_logo'], array( 'test_form' => false ) );
		}
		if( $uploaded_file && ! isset( $uploaded_file['error'] ) ) {
			$response['response'] = "SUCCESS";
			$response['filename'] = basename( $uploaded_file['url'] );
			$response['url'] = $uploaded_file['url'];
      $response['type'] = $uploaded_file['type'];
		} else {
			$response['response'] = "ERROR";
			$response['error'] = $uploaded_file['error'];
		}
	} elseif ( $usingUploader == 2) {
		if(isset($data['user_brand_banner'])){
			$attachment_id = media_handle_upload( 'user_brand_banner', 0 );
		} else {
			$attachment_id = media_handle_upload( 'user_brand_logo', 0 );
		}
		
		if ( is_wp_error( $attachment_id ) ) { 
			$response['response'] = "ERROR";
      $response['error'] = $fileErrors[ $data['user_brand_banner']['error'] ];
		} else {
			$fullsize_path = get_attached_file( $attachment_id );
			$pathinfo = pathinfo( $fullsize_path );
			$url = wp_get_attachment_url( $attachment_id );
			$response['response'] = "SUCCESS";
			$response['filename'] = $pathinfo['filename'];
			$response['url'] = $url;
			if(isset($data['user_brand_banner'])){
				update_field( 'user_brand_banner',$url,'user_'.wp_get_current_user()->ID );
			} else {
				update_field( 'user_brand_logo',$url,'user_'.wp_get_current_user()->ID );
			}
			$type = $pathinfo['extension'];
			if( $type == "jpeg"
			|| $type == "jpg"
			|| $type == "png"
			|| $type == "gif" ) {
				$type = "image/" . $type;
			}
			$response['type'] = $type;
		}
	}
	echo json_encode( $response );
	die();
}

Tags:

Restricting users to view only media library items they have uploaded

PHP
<?php
function users_own_attachments( $wp_query_obj ) {
    global $current_user, $pagenow;
    $is_attachment_request = ($wp_query_obj->get('post_type')=='attachment');
    if( !$is_attachment_request )
        return;
    if( !is_a( $current_user, 'WP_User') )
        return;
    if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) ) )
        return;
    if( !current_user_can('delete_pages') )
        $wp_query_obj->set('author', $current_user->ID );
    return;
}
add_action('pre_get_posts','users_own_attachments');

Tags: