|
<?php |
|
/* |
|
Plugin Name: Unauthorized Media Upload |
|
*/ |
|
add_action('rest_api_init', function () { |
|
register_rest_route('unauthorized-upload/v1', '/media', array( |
|
'methods' => 'POST', |
|
'callback' => 'unauthorized_upload', |
|
)); |
|
}); |
|
|
|
function unauthorized_upload() { |
|
if (!function_exists('wp_handle_upload')) { |
|
require_once ABSPATH . 'wp-admin/includes/file.php'; |
|
} |
|
|
|
$upload_overrides = array('test_form' => false); |
|
|
|
$data = array(); |
|
|
|
foreach ($_FILES as $key => $uploadedfile) { |
|
|
|
$movefile = wp_handle_upload($uploadedfile, $upload_overrides); |
|
|
|
$data[$key] = $movefile; |
|
|
|
} |
|
|
|
// Create the response object |
|
$response = new WP_REST_Response($data); |
|
|
|
// Add a custom status code |
|
$response->set_status(201); |
|
|
|
return $response; |
|
} |
|
|
|
function insert_to_media($filename, $parent_post_id) { |
|
|
|
// Check the type of file. We'll use this as the 'post_mime_type'. |
|
$filetype = wp_check_filetype(basename($filename), null); |
|
|
|
// Get the path to the upload directory. |
|
$wp_upload_dir = wp_upload_dir(); |
|
|
|
// Prepare an array of post data for the attachment. |
|
$attachment = array( |
|
'guid' => $wp_upload_dir['url'] . '/' . basename($filename), |
|
'post_mime_type' => $filetype['type'], |
|
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), |
|
'post_content' => '', |
|
'post_status' => 'inherit', |
|
); |
|
|
|
// Insert the attachment. |
|
$attach_id = wp_insert_attachment($attachment, $filename, $parent_post_id); |
|
if ($parent_post_id) { |
|
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. |
|
require_once ABSPATH . 'wp-admin/includes/image.php'; |
|
|
|
// Generate the metadata for the attachment, and update the database record. |
|
$attach_data = wp_generate_attachment_metadata($attach_id, $filename); |
|
wp_update_attachment_metadata($attach_id, $attach_data); |
|
|
|
set_post_thumbnail($parent_post_id, $attach_id); |
|
} |
|
} |