830 | | * Downloads an image from the specified URL and attaches it to a post. |
831 | | * |
832 | | * @since 2.6.0 |
833 | | * @since 4.2.0 Introduced the `$return` parameter. |
834 | | * |
835 | | * @param string $file The URL of the image to download. |
836 | | * @param int $post_id The post ID the media is to be associated with. |
837 | | * @param string $desc Optional. Description of the image. |
838 | | * @param string $return Optional. Accepts 'html' (image tag html) or 'src' (URL). Default 'html'. |
839 | | * @return string|WP_Error Populated HTML img tag on success, WP_Error object otherwise. |
840 | | */ |
841 | | function media_sideload_image( $file, $post_id, $desc = null, $return = 'html' ) { |
842 | | if ( ! empty( $file ) ) { |
843 | | |
844 | | // Set variables for storage, fix file filename for query strings. |
845 | | preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches ); |
846 | | $file_array = array(); |
847 | | $file_array['name'] = basename( $matches[0] ); |
848 | | |
849 | | // Download file to temp location. |
850 | | $file_array['tmp_name'] = download_url( $file ); |
851 | | |
852 | | // If error storing temporarily, return the error. |
853 | | if ( is_wp_error( $file_array['tmp_name'] ) ) { |
854 | | return $file_array['tmp_name']; |
855 | | } |
856 | | |
857 | | // Do the validation and storage stuff. |
858 | | $id = media_handle_sideload( $file_array, $post_id, $desc ); |
859 | | |
860 | | // If error storing permanently, unlink. |
861 | | if ( is_wp_error( $id ) ) { |
862 | | @unlink( $file_array['tmp_name'] ); |
863 | | return $id; |
864 | | } |
865 | | |
866 | | $src = wp_get_attachment_url( $id ); |
867 | | } |
868 | | |
869 | | // Finally, check to make sure the file has been saved, then return the HTML. |
870 | | if ( ! empty( $src ) ) { |
871 | | if ( $return === 'src' ) { |
872 | | return $src; |
873 | | } |
874 | | |
875 | | $alt = isset( $desc ) ? esc_attr( $desc ) : ''; |
876 | | $html = "<img src='$src' alt='$alt' />"; |
877 | | return $html; |
878 | | } else { |
879 | | return new WP_Error( 'image_sideload_failed' ); |
880 | | } |
881 | | } |
882 | | |
883 | | /** |