Mặc định WP đã có hàm hỗ trợ ta chỉ việc sử dụng hàm: media_sideload_image
Chi tiết cách sử dụng đươc thể hiện qua các ví dụ sau:

  1. Tạo ra thẻ html image từ url image
  2. Tạo ra đường dẫn hình ảnh mới
  3. Trả về id hình ảnh: sử dụng trường hợp lấy id hình ảnh vd: thiết lập ảnh đại diện cho bài viết…

Tạo ra thẻ html image từ url image

function maoht_download_image_from_external_url( $url ){
	// lib download media WP		
	require_once(ABSPATH . 'wp-admin/includes/media.php');
	require_once(ABSPATH . 'wp-admin/includes/file.php');
	require_once(ABSPATH . 'wp-admin/includes/image.php');

	$url     = 'https://huynhtanmao.com/wp-content/uploads/2019/11/maodev_sign.jpeg';
	$post_id = null ; // null or $post_id
	$alt     = ''		 ;// null or alt cua hinh anh 
	$return  = 'html';
	$html_img = media_sideload_image( $url, $post_id , $alt, $return );
	var_dump( $html_img );
}

Tạo ra đường dẫn hình ảnh mới

function maoht_renew_image_url_from_external_url( $url ){
	// lib download media WP		
	require_once(ABSPATH . 'wp-admin/includes/media.php');
	require_once(ABSPATH . 'wp-admin/includes/file.php');
	require_once(ABSPATH . 'wp-admin/includes/image.php');

	$url     = 'https://huynhtanmao.com/wp-content/uploads/2019/11/maodev_sign.jpeg';
	$post_id = null ; // null or $post_id
	$alt     = ''		 ;// null or alt cua hinh anh 
	$return  = 'url';
	$html_img = media_sideload_image( $url, $post_id , $alt, $return );
	var_dump( $html_img );
}

Trả về id hình ảnh: vd: thiết lập ảnh đại diện cho bài viết…

function maoht_return_id_image_url_from_external_url( $url ){
	// lib download media WP		
	require_once(ABSPATH . 'wp-admin/includes/media.php');
	require_once(ABSPATH . 'wp-admin/includes/file.php');
	require_once(ABSPATH . 'wp-admin/includes/image.php');

	$url     = 'https://huynhtanmao.com/wp-content/uploads/2019/11/maodev_sign.jpeg';
	$post_id = null ; // null or $post_id
	$alt     = ''		 ;// null or alt cua hinh anh 
	$return  = 'id';
	$html_img = media_sideload_image( $url, $post_id , $alt, $return );
	var_dump( $html_img );
}

Bài viết liên quan

post-no-image

Chia sẻ một số thư viện loading css đẹp

post-no-image

Một số css tùy biến thẻ input type: select, number

post-no-image

Tắt lazyload cho một số hình ảnh

post-no-image

Tuỳ biến layout YITH WooCommerce Wishlist

post-no-image

Một số hook hoặc filter thường sử dụng trong plugin WPML

post-no-image

Cách thay đổi parameter của url trong javascript