Skip to content

Instantly share code, notes, and snippets.

@nczz
Last active March 6, 2020 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nczz/610d29b8c3d9218c4d9412611f522cdb to your computer and use it in GitHub Desktop.
Save nczz/610d29b8c3d9218c4d9412611f522cdb to your computer and use it in GitHub Desktop.
WordPress 下載檔案存回媒體庫的方法
<?php
$link = '下載連結';
$file_name = '檔案名稱';
$upload_file = array();
$options = array('timeout' => 300);
$response = wp_safe_remote_get($link, $options);
$data = wp_remote_retrieve_body($response);
$upload_file[] = wp_upload_bits($file_name, null, $data);
$pid = '該篇文章ID';
for ($i = 0; $i < count($upload_file); ++$i) {
if (!$upload_file[$i]['error']) {
$wp_filetype = 'image/jpeg' //or image/png //wp_check_filetype($filename[$i], null);
$attachment = array(
'post_mime_type' => $wp_filetype,
'post_parent' => $pid,
'post_author' => '作者ID',
'post_title' => '',
'post_content' => '',
'post_status' => 'inherit',
);
$attachment_id = wp_insert_attachment($attachment, $upload_file[$i]['file'], $pid);
if (!is_wp_error($attachment_id)) {
//產生附加檔案中繼資料
$attachment_data = wp_generate_attachment_metadata($attachment_id, $upload_file[$i]['file']);
wp_update_attachment_metadata($attachment_id, $attachment_data);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment