Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 11 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
| MediaService | |
0.00% |
0 / 11 |
|
0.00% |
0 / 1 |
20 | |
0.00% |
0 / 1 |
| import_image_from_url | |
0.00% |
0 / 11 |
|
0.00% |
0 / 1 |
20 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace NewfoldLabs\WP\Module\Onboarding\Services; |
| 4 | |
| 5 | /** |
| 6 | * Media Service Class |
| 7 | * |
| 8 | * Handles media operations. |
| 9 | */ |
| 10 | class MediaService { |
| 11 | |
| 12 | /** |
| 13 | * Imports an image from a URL to the media library. |
| 14 | * |
| 15 | * @param string $image_url The URL of the image. |
| 16 | * @param int $post_id The ID of the post. |
| 17 | * @return array|false Array of the attachment id and src url or false if the image fails to import. |
| 18 | */ |
| 19 | public static function import_image_from_url( string $image_url, int $post_id = 0 ) { |
| 20 | if ( ! function_exists( 'media_handle_sideload' ) ) { |
| 21 | require_once( ABSPATH . 'wp-admin/includes/media.php' ); |
| 22 | require_once( ABSPATH . 'wp-admin/includes/file.php' ); |
| 23 | require_once( ABSPATH . 'wp-admin/includes/image.php' ); |
| 24 | } |
| 25 | |
| 26 | $attachment_id = media_sideload_image( $image_url, $post_id, null, 'id' ); |
| 27 | if ( is_wp_error( $attachment_id ) ) { |
| 28 | return false; |
| 29 | } |
| 30 | |
| 31 | $attachment_src = wp_get_attachment_url( $attachment_id ); |
| 32 | if ( ! $attachment_src ) { |
| 33 | return false; |
| 34 | } |
| 35 | |
| 36 | return array( 'id' => $attachment_id, 'src' => $attachment_src ); |
| 37 | } |
| 38 | } |