wordpress plugin file upload and email attachment form code example

Example 1: how to upload file in wordpress

class WLSM_Helper {

    public static function get_attachment_mime() {
		return array('image/jpg', 'image/jpeg', 'image/png', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/x-rar-compressed', 'application/octet-stream', 'application/zip', 'application/octet-stream', 'application/x-zip-compressed', 'multipart/x-zip', 'video/x-flv', 'video/mp4', 'application/x-mpegURL', 'video/MP2T', 'video/3gpp', 'video/quicktime', 'video/x-msvideo', 'video/x-ms-wmv');
	}

	public static function is_valid_file( $file, $type = 'attachment' ) {
		$get_mime = 'get_' . $type . '_mime';

		if ( extension_loaded( 'fileinfo' ) ) {
			$finfo = finfo_open( FILEINFO_MIME_TYPE );
			$mime  = finfo_file( $finfo, $file['tmp_name'] );
			finfo_close( $finfo );

		} else {
			$mime = $file['type'];
		}

		if ( ! in_array( $mime, self::$get_mime() ) ) {
			return false;
		}

		return true;
	}
}


# use helper class to organize your code

$attachment = (isset($_FILES['attachment']) && is_array($_FILES['attachment'])) ? $_FILES['attachment'] : NULL;

if (isset($attachment['tmp_name']) && !empty($attachment['tmp_name'])) {
    if (!WLSM_Helper::is_valid_file($attachment, 'attachment')) {
        $errors['attachment'] = esc_html__('This file type is not allowed.', 'school-management');
    }
}

$attachment = media_handle_upload('attachment', 0);
if (is_wp_error($attachment)) {
    throw new Exception($attachment->get_error_message());
}
$data['attachment'] = $attachment;

Example 2: image upload and get attachment id in wordpress

/* this function for upload image in wordpress and return attchement id code by joshi yogesh ([email protected])*/
function cst_image_upload($img){

    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $attes_id = array();
    $cnt = count($img['name']);
    for($i=0;$i<$cnt;$i++)
    {
            $name = $img['name'][$i];
            $type = $img['type'][$i];
            $tmp_name = $img['tmp_name'][$i];
            $error = $img['error'][$i];
            $size = $img['size'][$i] ;
        
        $upload_data = array(
            'name'      => $name,
            'type'      => $type,
            'tmp_name'  => $tmp_name,
            'error'     => $error,
            'size'      => $size
            );
        $uploaded_file = wp_handle_upload($upload_data, array('test_form' => false));
        // print_r($uploaded_file);

        if (isset($uploaded_file['file'])) {
            $file_loc   =   $uploaded_file['file'];
            $file_name  =   basename($upload_data['name']);
            $file_type  =   wp_check_filetype($file_name);

            $attachment = array(
                'post_mime_type'    => $file_type['type'],
                'post_title'        => preg_replace('/\.[^.]+$/', '', basename($file_name)),
                'post_content'      => '',
                'post_status'       => 'inherit'
            );

            $attach_id      =   wp_insert_attachment($attachment, $file_loc);
            $attach_data    =   wp_generate_attachment_metadata($attach_id, $file_loc);
            wp_update_attachment_metadata($attach_id, $attach_data);
            array_push($attes_id,$attach_id);
        }
    }
    return $attes_id;
}

Tags:

Php Example