問題描述

在瀏覽 function reference entry for wp_insert_post()的同時,我注意到數組中沒有任何參數,這將允許我設置一個帖子的’Featured Image’,在我的主題中顯示為 post thumbnail

我已經研究了像 Bennett 先生的建議的 set_post_thumbnail()這樣的功能,但這似乎是 WordPress 本身和 WordPress 的一個比較新的補充。因此,沒有任何來源可以找到哪些解釋如何獲取和提供 $ thumbnail_id 參數。如果這真的是使用的功能,當我所有的都是一個圖像 URL 時,我可以以什麼方式提供一個有效的 $ thumbnail_id 參數?

提前致謝!

最佳解決方案

您可以將圖像設置為您的媒體庫中的縮略圖。要在媒體庫中添加圖像,您需要將其上傳到您的服務器。 WordPress 已經具有將圖像放入媒體庫的功能,您只需要一個腳本來上傳您的文件。

用法:

Generate_Featured_Image( '../wp-content/my_image.jpg',   $post_id );
                                                      // $post_id is Numeric ID... You can also get the ID with:          wp_insert_post()

功能:

function Generate_Featured_Image( $image_url, $post_id  ){
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
    if(wp_mkdir_p($upload_dir['path']))     $file = $upload_dir['path'] . '/' . $filename;
    else                                    $file = $upload_dir['basedir'] . '/' . $filename;
    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
    $res2= set_post_thumbnail( $post_id, $attach_id );
}

 http://codex.wordpress.org/Function_Reference/wp_upload_dir

 http://codex.wordpress.org/Function_Reference/wp_insert_attachment


編輯:添加路徑創建

 http://codex.wordpress.org/Function_Reference/wp_mkdir_p

次佳解決方案

嘗試使用 set_post_thumbnail()

Otto 編輯:你澄清了你的問題,所以我將澄清 Chip 給出的回應。

基本上,您還需要使’attachment’ 成為該職位。當圖像上傳到 WordPress 媒體庫中時,會使用後綴類型的附件進行特殊的條目。此附件通過 post_parent 標識符鏈接到某些特定的帖子。

所以如果你知道附件的 ID,那麼使用 post 對象或 ID 和附件 ID 調用 set_post_thumbnail 就可以簡單地設置 post thumbnail 標誌。

如果您尚未創建附件,那麼您需要首先執行。最簡單的方法是用 wp_insert_attachment()。此函數需要一個數組的幾個參數,文件名 (該文件必須在適當的 uploads 目錄中),以及要附加附件的父帖子的帖子 ID 。

只需將文件上傳並附加到帖子就不會自動執行任何操作。這只是一種分類機制。例如,圖庫機制使用附件的帖子來構建該帖子的。帖子的縮略圖只是附加圖像之一,已被設置為縮略圖。

有關如何使用 wp_insert_attachment 的更多信息,可以在 codex(上面鏈接) 中找到。

第三種解決方案

我想通過使用 WP 核心功能 download_urlmedia_handle_sideload 來改善 Robs 的答案

<?php
/**
* Downloads an image from the specified URL and attaches it to a post as a post thumbnail.
*
* @param string $file    The URL of the image to download.
* @param int    $post_id The post ID the post thumbnail is to be associated with.
* @param string $desc    Optional. Description of the image.
* @return string|WP_Error Attachment ID, WP_Error object otherwise.
*/
function Generate_Featured_Image( $file, $post_id, $desc ){
    // Set variables for storage, fix file filename for query strings.
    preg_match( '/[^?]+.(jpe?g|jpe|gif|png)b/i', $file, $matches );
    if ( ! $matches ) {
         return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) );
    }

    $file_array = array();
    $file_array['name'] = basename( $matches[0] );

    // Download file to temp location.
    $file_array['tmp_name'] = download_url( $file );

    // If error storing temporarily, return the error.
    if ( is_wp_error( $file_array['tmp_name'] ) ) {
        return $file_array['tmp_name'];
    }

    // Do the validation and storage stuff.
    $id = media_handle_sideload( $file_array, $post_id, $desc );

    // If error storing permanently, unlink.
    if ( is_wp_error( $id ) ) {
        @unlink( $file_array['tmp_name'] );
        return $id;
    }
    return set_post_thumbnail( $post_id, $id );

}

參考文獻

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