Php Wordpress-使用URL中的图像作为帖子缩略图
我想使用URL中的外部图像作为帖子缩略图,但我不想下载图像并将其存储在我的服务器中 我在另一个问题中发现了这个代码:Php Wordpress-使用URL中的图像作为帖子缩略图,php,wordpress,api,plugins,Php,Wordpress,Api,Plugins,我想使用URL中的外部图像作为帖子缩略图,但我不想下载图像并将其存储在我的服务器中 我在另一个问题中发现了这个代码: $filename = "thumbnail_".$post_id".jpg"; $upload_file = wp_upload_bits( $filename, null, @file_get_contents('http://example.com/image.jpg') ); if ( ! $upload_file['e
$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 );
}
}
它将图像下载到我的服务器,并在我的上传目录中复制图像文件(我不知道为什么)
但我不想下载图像如何实现这一点?我还没有测试过这一点,但假设您总是想要相同的文件,这可能会帮助您开始:
$filepath = 'http://example.com/'; //Change this to the actual file path...
$filename = 'image.jpg'; //Change this to the actual file name...
$filetype = wp_check_filetype( basename( $filename ), null );
$attachment = array(
'guid' => $filepath . $filename,
'post_mime_type' => $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 );
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 );
}
假设此图像只是特色图像的替代品-您可以将图像源的URL存储在自定义字段中
add_post_meta($post_id,'image','http://example.com/image.jpg' );代码>
然后,您可以在任何需要的地方检索此URL。这仍将下载图像。他不想这样。我没有亲自测试,但出于好奇,这张图片还在哪里下载和上传?这意味着将外部URL和文件写入GUID字段,创建新的附件帖子,并将其与现有帖子关联。代码中没有可下载或上载的内容。wp\u insert\u附件
将此图像添加到库中。无论如何,你的代码并没有错——这不是门塔马林多所要求的。当我有时间的时候,我会测试你的代码,看看是否有一个唯一的URL可以注册到图片中,而不需要把它放到主机上。从我对这个问题的阅读中,我认为它特别想把URL和post_缩略图联系起来——我一直都是这样做的,如果我想添加一个替代图片,就把它作为post_meta添加。我想测试一下自己,但我完全被淹没了。英雄联盟我认为有一种方法可以更改图像源URL并将其保留在库中。S3卸载介质以某种方式实现了这一点。这么多的工作正在进行-在墙上!好的,我试图检索如下内容:get_post_meta(the_ID(),'image',true);?>
但它返回的是实际的帖子ID而不是图像url,知道吗?我把代码放在这里:“/>
ID()
应该是获取ID()
没问题,很乐意帮助:)这确实有效,但您的问题最初是要求添加一个外部图像URL作为指定的帖子缩略图/附件。这是帖子元数据,从技术上讲不是帖子缩略图。如果您使用帖子缩略图(),这将不起作用。