问题描述

给定 Vimeo ID,我可以通过 Vimeo Simple API 从视频中检索缩略图。不要每次加载页面时调用 API,而是使用 save_post 钩子 (类似于 this question) 将图像设置为帖子缩略图。

我的问题是我不熟悉 php 中的 URL 调用。我想知道:

  1. WP_Http 相比,使用 curl 方法的优点/缺点。是一个”better” 比其他?

  2. 我应该调用函数的顺序来成功设置帖子缩略图。

任何帮助将不胜感激。

最佳解决方案

我最喜欢的处理这个问题的方法是使用我在另一个堆栈文件中发现的一点文档功能:media_sideload_image

它通过将图像 url 获取到 WordPress 上传目录,然后将图像与帖子的附件相关联。

你可以这样尝试:

// required libraries for media_sideload_image
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

// $post_id == the post you want the image to be attached to
// $video_thumb_url == the vimeo video's thumb url
// $description == optional description

// load the image
$result = media_sideload_image($video_thumb_url, $description);

// then find the last image added to the post attachments
$attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));


if(sizeof($attachments) > 0){
    // set image as the post thumbnail
    set_post_thumbnail($post_id, $attachments[0]->ID);
}

次佳解决方案

嗨 @David 约翰·史密斯:

1.) 如果你在 WordPress,(几乎) 总是使用 WP_Http; 它是我喜欢使用 WordPress 的许多事情之一。为什么叫它而不是 CURL?那么,因为它有一个更好的语法,如果 CURL 可用,它会调用 CURL 。如果没有,它从 3 个其他选项之一中选择。所以它真的是一个辉煌的工具包。

2.) 要回答第二个问题,我需要知道你想要下载的文件的名称。

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。