Skip to content

Instantly share code, notes, and snippets.

@nczz
Created April 14, 2017 12:25
Show Gist options
  • Save nczz/ae98d4863a299414ef0ca7627844ed8e to your computer and use it in GitHub Desktop.
Save nczz/ae98d4863a299414ef0ca7627844ed8e to your computer and use it in GitHub Desktop.
使用遠端圖片連結建立文章特色圖片(thumbnail)
<?php
//functions.php
function mxp_set_remote_image_to_post_thumbnail($post_id) {
$link = get_post_meta($post_id, 'mxp-remote-image', true);
if (filter_var($link, FILTER_VALIDATE_URL) === FALSE) {
return false;
}
if (!has_post_thumbnail($post_id)) {
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
$filename = basename(parse_url($link, PHP_URL_PATH));
$upload_file = wp_upload_bits($filename, null, file_get_contents($link));
if (!$upload_file['error']) {
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $post_id,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => $filename,
'post_status' => 'inherit',
);
$attachment_id = wp_insert_attachment($attachment, $upload_file['file'], $post_id);
if (!is_wp_error($attachment_id)) {
//產生附加檔案中繼資料
$attachment_data = wp_generate_attachment_metadata($attachment_id, $upload_file['file']);
wp_update_attachment_metadata($attachment_id, $attachment_data);
//將圖像的附加檔案設為特色圖片
$type = explode("/", $wp_filetype['type']);
if ($type[0] == 'image') {
set_post_thumbnail($post_id, $attachment_id);
}
}
}
return $attachment_id;
} else {
return false;
}
}
add_action('save_post', 'mxp_set_remote_image_to_post_thumbnail', 10, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment