Skip to content

Instantly share code, notes, and snippets.

@campusboy87
Created December 18, 2018 16:57
Show Gist options
  • Save campusboy87/3c2efde2945f1d4e8abe1336c875d05f to your computer and use it in GitHub Desktop.
Save campusboy87/3c2efde2945f1d4e8abe1336c875d05f to your computer and use it in GitHub Desktop.
<?php
/**
* Загружает изображение в медиабиблиотеку по переданному url.
*
* @param string $url
* @param int $post_id
*
* @return int|WP_Error
*/
protected function media_sideload_image( $url, $post_id = 0 ) {
$file_array = [];
// Download file to temp location.
$file_array['tmp_name'] = download_url( $url );
// If error storing temporarily, return the error.
if ( is_wp_error( $file_array['tmp_name'] ) ) {
return $file_array['tmp_name'];
}
$ext = strtok( array_search( mime_content_type( $file_array['tmp_name'] ), get_allowed_mime_types() ), '|' );
$file_array['name'] = basename( $url ) . ( $ext ? ".$ext" : '' );
// Do the validation and storage stuff.
$id = media_handle_sideload( $file_array, $post_id );
// If error storing permanently, unlink.
if ( is_wp_error( $id ) ) {
@unlink( $file_array['tmp_name'] );
return $id;
// If attachment id was requested, return it early.
} else {
return $id;
}
}
@mihdan
Copy link

mihdan commented Dec 18, 2018

А почему ты удаляешь временный файл только при ошибке, а при успехе?

@campusboy87
Copy link
Author

А почему ты удаляешь временный файл только при ошибке, а при успехе?

Потому что при успехе media_handle_sideload() сама это сделает.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment