campusboy87
12/18/2018 - 4:57 PM

media_sideload_image.php

<?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;
    }
}