問題描述

在使用媒體上傳螢幕上傳 WordPress 中的附件後,是否有可以在上傳影像之後執行的掛鉤或過濾器,以便我可以獲取上傳影像的路徑,以便我可以分析?

我正在構建一個外掛,將在上傳影像後分析影像,然後使用影像中找到的平均顏色標記影像。唯一的問題是我不知道我可以使用哪個 hook,它將在影像上傳後立即開始,然後以一種方式獲得新上傳的檔案的路徑。

任何幫助將非常感激。

最佳解決方案

原來我在同事的幫助下解決了自己的問題。在媒體被上傳或媒體被編輯之後被呼叫的兩個過濾器是; ‘add_attachment’ 和’edit_attachment’ 。這是我使用的程式碼,然後檢查附件是否是一個影像 (程式碼從示例中省略) 。

function analyse_attachment($attachment_ID)
{          
    $attachment = get_attached_file($attachment_ID); // Gets path to attachment
    update_post_meta($attachment_ID, "image_rgb", $the_colour);
}

add_action("add_attachment", 'analyse_attachment');
add_action("edit_attachment", 'analyse_attachment');

顯然我省略了一些與這個問題無關的東西。但是,在您上傳或編輯附件之後,該程式碼才會被呼叫。

次佳解決方案

你有兩個可以使用的過濾器:attachment_fields_to_save 它得到兩個引數 ($ post,$ attachment) 所以:

add_filter('attachment_fields_to_save',your_image_analyse_function);

function your_image_analyse_function($post, $attachment){
  $attachment['url']
  //do your stuff
}

media_send_to_editor,它獲得 3 個引數 ($ html,$ send_id,$ attachment),並在您點選傳送到編輯器後再次觸發,可以使用 $附件。

add_filter('media_send_to_editor',your_image_analyse_function);

function your_image_analyse_function($html, $send_id, $attachment){
  $attachment['url']
  //do your stuff
}

參考文獻

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