Skip to content

Instantly share code, notes, and snippets.

@frontycore
Last active November 11, 2022 16:10
Show Gist options
  • Save frontycore/7789aa1bbcbca90b9b5a8d73b327ffdb to your computer and use it in GitHub Desktop.
Save frontycore/7789aa1bbcbca90b9b5a8d73b327ffdb to your computer and use it in GitHub Desktop.
Wordpress class to upload files from external URL to media library.
<?php
namespace App;
use RuntimeException;
require_once(ABSPATH . '/wp-load.php');
require_once(ABSPATH . '/wp-admin/includes/image.php');
require_once(ABSPATH . '/wp-admin/includes/file.php');
require_once(ABSPATH . '/wp-admin/includes/media.php');
class FileUploader
{
/** @var string */
private $url;
/**
* Set external URL.
* @param string $url
*/
public function __construct(string $url)
{
$this->url = $url;
}
/**
* Upload file.
* @param string|null $title
* @param array $meta
* @return int Attachment id.
* @throws RuntimeException
*/
public function upload(string $title = null, array $meta = []): int
{
$tmp = download_url($this->url);
if (is_wp_error($tmp)) throw new RuntimeException($tmp->get_error_message(), $tmp->get_error_code());
$filename = pathinfo($this->url, PATHINFO_FILENAME);
$extension = pathinfo($this->url, PATHINFO_EXTENSION);
if (!$extension) $extension = $this->getMimeExtension($tmp);
if (!$extension) {
@unlink($tmp);
throw new RuntimeException('Unknown file extension.');
}
$imgId = media_handle_sideload([
'name' => "$filename.$extension",
'tmp_name' => $tmp,
], 0, $title);
@unlink($tmp);
if (is_wp_error($imgId)) throw new RuntimeException($imgId->get_error_message(), $imgId->get_error_code());
foreach ($meta as $key => $value) {
update_post_meta($imgId, $key, $value);
}
return $imgId;
}
/**
* Get file extension by mime type.
* @param string $path
* @return string|null
*/
private function getMimeExtension(string $path): ?string
{
$mime = mime_content_type($path);
$mime = is_string($mime) ? sanitize_mime_type($mime) : false;
$mimeExts = array(
'text/plain'=> 'txt',
'text/csv' => 'csv',
'application/msword' => 'doc',
'image/jpg' => 'jpg',
'image/jpeg' => 'jpeg',
'image/gif' => 'gif',
'image/png' => 'png',
'video/mp4' => 'mp4'
);
if (isset($mimeExts[$mime])) return $mimeExts[$mime];
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment