php - Wordpress - Use image from URL as a post thumbnail
问题描述
I want to use an external image from URL as a post thumbnail, BUT I don't want to download and store the image in my server
I'm found this code in other guy question:
$filename = "thumbnail_".$post_id".jpg";
$upload_file = wp_upload_bits( $filename, null, @file_get_contents('http://example.com/image.jpg') );
if ( ! $upload_file['error'] ) {
$filename = $upload_file['file'];
$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' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
file_put_contents('attachment_id.txt', print_r($attachment_id, true));
if ( ! is_wp_error( $attachment_id ) ) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
set_post_thumbnail( $post_id, $attachment_id );
}
}
It downloads the image to my server and also duplicates the image file in my uploads directory (I don't know why)
But I don't wanna download the image how can I achieve this?
解决方案
Assuming this image is just alternative to the featured image - you could store the URL of the image source in the custom field.
add_post_meta( $post_id, 'image', 'http://example.com/image.jpg' );
Then you can retrieve this URL anywhere you need to.
推荐阅读
- playback - MP3 文件在页面中不播放我的意思是自动播放失败
- spring - Spring MVC 将枚举绑定到输入
- javascript - 我想在 vue js 中玩一个动态类
- hibernate - QueryDSL CaseBuilder 不适用于 java.util.Date
- javascript - 如何在 OpenLayers 中重叠或相同几何体的情况下选择哪个要素叠加
- python - 使用 python-chess 从 PGN 文件中提取移动作为字符串
- reactjs - 部署在 Heroku 上的 ExpressJS API 出现 500 内部服务器错误
- excel - 类型不匹配 - 范围和数字
- javascript - 当对象是 JSON 对象与 Array 对象时,为什么 [For.. in] 循环中使用的变量返回不同的值?
- python - 在 python 中复制 F# map join