問題描述

給定 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。