Created
December 18, 2018 16:57
-
-
Save campusboy87/3c2efde2945f1d4e8abe1336c875d05f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* Загружает изображение в медиабиблиотеку по переданному 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; | |
} | |
} |
А почему ты удаляешь временный файл только при ошибке, а при успехе?
Потому что при успехе media_handle_sideload() сама это сделает.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
А почему ты удаляешь временный файл только при ошибке, а при успехе?