Created
March 7, 2024 04:17
-
-
Save aliboy08/d52542b8ffb83d84850768ab530d5c30 to your computer and use it in GitHub Desktop.
wp upload file to media library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Upload_File { | |
function upload_file( $file_url ) { | |
$path_info = pathinfo($file_url); | |
$file_name = $path_info['filename']; | |
$attachment_id = $this->get_attachment_id_by_filename($file_name); | |
if( !$attachment_id ) { | |
// does not exist yet, upload | |
$attachment_id = $this->upload_file_from_url($file_url); | |
} | |
return $attachment_id; | |
} | |
function upload_file_from_url( $file_url ) { | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
// download to temp dir | |
$temp_file = download_url( $file_url ); | |
if( is_wp_error( $temp_file ) ) return false; | |
// move the temp file into the uploads directory | |
$file = [ | |
'name' => basename( $file_url ), | |
'type' => mime_content_type( $temp_file ), | |
'tmp_name' => $temp_file, | |
'size' => filesize( $temp_file ), | |
]; | |
$sideload = wp_handle_sideload($file, ['test_form' => false]); | |
if( ! empty( $sideload[ 'error' ] ) ) return false; | |
// add to media library | |
$attachment_id = wp_insert_attachment( | |
[ | |
'guid' => $sideload[ 'url' ], | |
'post_mime_type' => $sideload[ 'type' ], | |
'post_title' => basename( $sideload[ 'file' ] ), | |
'post_content' => '', | |
'post_status' => 'inherit', | |
], | |
$sideload[ 'file' ] | |
); | |
if( is_wp_error( $attachment_id ) || ! $attachment_id ) { | |
return false; | |
} | |
// update medatata, regenerate image sizes | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
wp_update_attachment_metadata( | |
$attachment_id, | |
wp_generate_attachment_metadata( $attachment_id, $sideload[ 'file' ] ) | |
); | |
return $attachment_id; | |
} | |
function get_attachment_id_by_filename($file_name){ | |
global $wpdb; | |
$result = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%s' LIMIT 1;", '%' . $wpdb->esc_like($file_name) . '%' )); | |
if( $result ) { | |
return $result[0]; | |
} | |
return false; | |
} | |
} | |
$uploader = new Upload_File(); | |
$uploader->upload_file('file_url_here'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment