問題描述

如果我建立了一個包含嵌入式 YouTube 影片的帖子 (所以我所做的就是將 YouTube 網址貼上到帖子中,讓 Wordpress 自動為我嵌入),是否有一種方法可以將影片的縮圖設定為該帖子的特色圖片?

最佳解決方案

不是天生的。您必須編寫一些程式碼才能實現 – 有一個很好的 pastebin 函式可以提供必要的程式碼來實現。

編輯 (12/19/2011):

這是你可以用程式設計方式來做的。將以下兩個函式新增到 functions.php 檔案中,你應該很好去。該程式碼已被評論以解釋發生了什麼,但這裡有很高的期望值:

你必須…

  • 建立一個帖子

  • 內容中包含 YouTube 網址

程式碼將…

  • 解析 URL 中的內容

  • 將抓住它找到的第一個網址,並認為它是一個 YouTube 網址

  • 從遠端伺服器抓取縮圖並下載

  • 將其設定為當前帖子的縮圖

請注意,如果您的帖子中包含多個網址,則需要修改程式碼才能正確找到 YouTube 網址。這可以透過迭代 $attachments 集合並嗅探出 URL 的外觀。

function set_youtube_as_featured_image($post_id) {

    // only want to do this if the post has no thumbnail
    if(!has_post_thumbnail($post_id)) {

        // find the youtube url
        $post_array = get_post($post_id, ARRAY_A);
        $content = $post_array['post_content'];
        $youtube_id = get_youtube_id($content);

        // build the thumbnail string
        $youtube_thumb_url = 'http://img.youtube.com/vi/' . $youtube_id . '/0.jpg';

        // next, download the URL of the youtube image
        media_sideload_image($youtube_thumb_url, $post_id, 'Sample youtube image.');

        // find the most recent attachment for the given post
        $attachments = get_posts(
            array(
                'post_type' => 'attachment',
                'numberposts' => 1,
                'order' => 'ASC',
                'post_parent' => $post_id
            )
        );
        $attachment = $attachments[0];

        // and set it as the post thumbnail
        set_post_thumbnail( $post_id, $attachment->ID );

    } // end if

} // set_youtube_as_featured_image
add_action('save_post', 'set_youtube_as_featured_image');

function get_youtube_id($content) {

    // find the youtube-based URL in the post
    $urls = array();
    preg_match_all('#bhttps?://[^s()<>]+(?:([wd]+)|([^[:punct:]s]|/))#', $content, $urls);
    $youtube_url = $urls[0][0];

    // next, locate the youtube video id
    $youtube_id = '';
    if(strlen(trim($youtube_url)) > 0) {
        parse_str( parse_url( $youtube_url, PHP_URL_QUERY ) );
        $youtube_id = $v;
    } // end if

    return $youtube_id;

} // end get_youtube_id

有一點需要注意的是,這假設您的帖子沒有釋出縮圖,一旦設定了縮圖後,它不會觸發。

其次,如果您刪除帖子縮圖,然後使用媒體上傳器將影像附加到此帖子,則將使用最新的影像。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。