| 1 |
<?php |
| 2 |
/** |
| 3 |
* Import image |
| 4 |
* |
| 5 |
* @package WPFunnels\Importer\Image |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WPFunnels\Importer\Image; |
| 9 |
|
| 10 |
use WP_Http; |
| 11 |
|
| 12 |
/** |
| 13 |
* Import image |
| 14 |
* |
| 15 |
* @since 1.0.0 |
| 16 |
*/ |
| 17 |
class Wpfnl_Image_Importer { |
| 18 |
|
| 19 |
/** |
| 20 |
* Class instance |
| 21 |
* |
| 22 |
* @var mixed |
| 23 |
*/ |
| 24 |
private static $instance; |
| 25 |
|
| 26 |
/** |
| 27 |
* Get Instance class |
| 28 |
* |
| 29 |
* @return Wpfnl_Image_Importer |
| 30 |
*/ |
| 31 |
public static function get_instance() { |
| 32 |
if ( ! isset( self::$instance ) ) { |
| 33 |
self::$instance = new self(); |
| 34 |
} |
| 35 |
|
| 36 |
return self::$instance; |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
/** |
| 41 |
* Import images |
| 42 |
* |
| 43 |
* @param string $image Image url. |
| 44 |
* |
| 45 |
* @return array|bool |
| 46 |
* @since 1.0.0 |
| 47 |
*/ |
| 48 |
public function import( $image ) { |
| 49 |
|
| 50 |
if ( !class_exists( 'WP_Http' ) ) { |
| 51 |
include_once ABSPATH . WPINC . '/class-http.php'; |
| 52 |
} |
| 53 |
|
| 54 |
$http = new WP_Http(); |
| 55 |
$response = $http->request( $image['url'] ); |
| 56 |
if ( is_wp_error( $response ) || 200 !== $response['response']['code'] ) { |
| 57 |
return false; |
| 58 |
} |
| 59 |
|
| 60 |
$upload = wp_upload_bits( basename( $image['url'] ), null, $response['body'] ); |
| 61 |
if ( !empty( $upload['error'] ) ) { |
| 62 |
return false; |
| 63 |
} |
| 64 |
|
| 65 |
$file_path = $upload['file']; |
| 66 |
$file_name = basename( $file_path ); |
| 67 |
$file_type = wp_check_filetype( $file_name, null ); |
| 68 |
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) ); |
| 69 |
$wp_upload_dir = wp_upload_dir(); |
| 70 |
|
| 71 |
$post_info = array( |
| 72 |
'guid' => $wp_upload_dir['url'] . '/' . $file_name, |
| 73 |
'post_mime_type' => $file_type['type'], |
| 74 |
'post_title' => $attachment_title, |
| 75 |
'post_content' => '', |
| 76 |
'post_status' => 'inherit', |
| 77 |
); |
| 78 |
|
| 79 |
// Create the attachment. |
| 80 |
$attachment_id = wp_insert_attachment( $post_info, $file_path ); |
| 81 |
|
| 82 |
// Include image.php. |
| 83 |
require_once ABSPATH . 'wp-admin/includes/image.php'; |
| 84 |
|
| 85 |
// Define attachment metadata. |
| 86 |
$attach_data = wp_generate_attachment_metadata( $attachment_id, $file_path ); |
| 87 |
|
| 88 |
// Assign metadata to attachment. |
| 89 |
wp_update_attachment_metadata( $attachment_id, $attach_data ); |
| 90 |
return array( |
| 91 |
'id' => $attachment_id, |
| 92 |
'url' => $upload['url'], |
| 93 |
); |
| 94 |
} |
| 95 |
} |
| 96 |
|