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:
- Tạo ra thẻ html image từ url image
- Tạo ra đường dẫn hình ảnh mới
- 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 );
}