問題描述

我想上傳一個圖像,並將其設置為一個特色的圖像在一個帖子。我試過的是這樣的:

$image_id = media_sideload_image($image_url, $post_id, $post_id);
update_post_meta($post_id, '_thumbnail_id', $image_id);

但是 media_sideload_image() 沒有返回 image_id,而是渲染 html 圖像。如何獲取 image_id?

最佳解決方案

以下是使用動作/鈎子繞過此限制的示例:

function new_attachment( $att_id ){
    // the post this was sideloaded into is the attachments parent!

    // fetch the attachment post
    $att = get_post( $att_id );

    // grab it's parent
    $post_id = $att->post_parent;

    // set the featured post
    set_post_thumbnail( $post_id, $att_id );
}

// add the function above to catch the attachments creation
add_action('add_attachment','new_attachment');

// load the attachment from the URL
media_sideload_image($image_url, $post_id, $post_id);

// we have the image now, and the function above will have fired too setting the thumbnail ID in the process, so lets remove the hook so we don't cause any more trouble
remove_action('add_attachment','new_attachment');

這個想法是當 media_sideload_image 運行時,它:

  • 下載圖片

  • 將其添加為附件 (attachment 類型的帖子)

  • 然後將附件附加到您提供的 ID 的帖子 ($ post_id)

您的問題是它不提供新創建的附件帖子 ID 。

但是,當創建附件時,會觸發一個包含其 ID 的操作。我們可以在創建附件之前勾選此內容,並使用它給我們的帖子 ID 保存特色縮略圖,然後取消掛起。

次佳解決方案

我已經建立了一個函數來獲取 DB 中的 ID,通過 URL 進行搜索。

function get_attachment_id_from_src ($image_src) {
  global $wpdb;
  $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
  $id = $wpdb->get_var($query);
  return $id;
}

你可以得到第四個參數設置為'src' Codex: media_sideload_image()的網址 (html 代碼)

$src = media_sideload_image($url, $item_id, $desc,'src');
get_attachment_id_from_src($src);

第三種解決方案

諾託維爾的答案是現在的。我發現另一個選擇 (使用不同的功能)explained here,但我更喜歡這一個。

在我的情況下,我有一個 $的帖子,我要插入的所有帖子和一個單獨的 $媒體 (與 $ posts 相同的 $ nid 鍵) 與媒體。我的代碼與 Tom 的解決方案是一樣的,但重構使用匿名函數:

foreach( $posts as $nid=>$post )
    $posts[$nid]['ID'] = wp_insert_post( $post );

foreach( $posts as $nid=>$post )
    foreach( $media[$nid] as $m=>$mitem ) {

        if( 0 == $m ) add_action( 'add_attachment',
            function( $att_id ) use ($posts, $nid, $mitem) {
                update_post_meta($posts[$nid]['ID'], '_thumbnail_id', $att_id);
                $posts[$nid]['media_urls'][] = $mitem['url'];
            }
        );
        media_sideload_image($mitem['url'], $post['ID']);
        remove_all_actions( 'add_attachment' );
    }

在我的情況下,我假設每個 $媒體 [$ nid] 中的第一個項目是他的帖子的特色圖像。

WordPress shouold 肯定會改變 media_sideload_image() 所以它返回 $ id 。實際上該功能已經在手邊,請參閲 source here 。實際上有一個 track ticket for this,如果你願意的話,他們甚至還有補丁應用到你的核心。

參考文獻

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