Tạo function tải và upload hình ảnh WordPress

Đoạn code dưới đây sẽ giúp bạn tải hình ảnh về và upload lên WordPress, và set hình ảnh đại diện, nó phù hợp với các bạn đang làm việc với crawl dữ liệu hoặc tự viết auto lấy nội dung và sản phẩm. Ngoài ra bạn có tùy biết đoạn code này thành function hoặc thêm nó vào trong plugin của mình.

// Code dẫn đến thư mục uploads
$upload_dir = wp_upload_dir();

// Set the file name and path
$filename = 'example-image.jpg';
$file_path = $upload_dir['path'] . '/' . $filename;

// URL to upload directory
$upload_url = $upload_dir['url'];

// Sample image URL to be downloaded
$image_url = 'https://www.example.com/path/to/your/image.jpg';

// Fetch the image data
$response = wp_remote_get($image_url);

if (!is_wp_error($response) && $response['response']['code'] === 200) {
// Get the image body/content
$image_data = wp_remote_retrieve_body($response);

// Upload the image using wp_upload_bits
$upload = wp_upload_bits($filename, null, $image_data, date('Y/m'));

if (!$upload['error']) {
// File successfully uploaded
$attachment = array(
'post_title' => sanitize_file_name($filename),
'post_mime_type' => 'image/jpeg', // Change mime type if necessary
'guid' => $upload_url . '/' . $filename,
'post_content' => '',
'post_status' => 'inherit'
);

// Insert the image as an attachment
$attachment_id = wp_insert_attachment($attachment, $file_path);

if (!is_wp_error($attachment_id)) {
// Generate metadata for the attachment and update it
require_once ABSPATH . 'wp-admin/includes/image.php';
$attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
wp_update_attachment_metadata($attachment_id, $attachment_data);

// Optionally set the image as the featured image for a post
// $post_id = 1; // Set your post ID here
// set_post_thumbnail($post_id, $attachment_id);

echo 'Image uploaded successfully!';
} else {
echo 'Error inserting attachment.';
}
} else {
echo 'Error uploading image: ' . $upload['error'];
}
} else {
echo 'Error fetching image.';
}

 

 

5/5 - (2 bình chọn)