WordPress: effettuare il download di immagini remote

WordPress ci permette di effettuare il dowload di immagini remote.

WordPress di Gabriele Romanato

WordPress ci permette di effettuare il dowload di immagini remote.

La soluzione รจ la seguente.


function my_download_image( $url ) {
    if( !filter_var( $url, FILTER_VALIDATE_URL ) ) {
        return null;
    }

	$response = wp_remote_get( $url );

    if( is_wp_error( $response ) ) {
        return null;
    }
    $download_dir = wp_upload_dir( date('Y/m', time() ) );
	$valid_extensions_map = array(
		'image/jpeg' => 'jpg',
		'image/png'  => 'png',
		'image/gif'  => 'gif',
		'image/bmp'  => 'bmp',
		'image/tiff' => 'tif'
	);
	$temp_file = tempnam( sys_get_temp_dir(), 'MY' );
	file_put_contents( $temp_file, $response['body'] );
	$mime = wp_get_image_mime( $temp_file );
	unlink( $temp_file );

    if( !isset( $valid_extensions_map[$mime] ) ) {
        return null;
    }

	$image = [];
	$image['mime_type'] = $mime;
	$image['ext'] = $valid_extensions_map[$mime];
	$image['filename'] = md5( uniqid() ) . '.' . $image['ext'];
	$image['base_path'] = rtrim( $download_dir['path'], DIRECTORY_SEPARATOR );
	$image['base_url'] = rtrim( $download_dir['url'], '/' );
	$image['path'] = $image['base_path'] . DIRECTORY_SEPARATOR . $image['filename'];
	$image['url'] = $image['base_url'] . '/' . $image['filename'];

	file_put_contents( $image['path'], $response['body'] );

	return $image;
}

Commenti