問題描述
我目前正在使用 WordPress 內置的 Custom Headers 來獲取我的網站主頁上的幻燈片圖像。在很大程度上,這是按照意圖工作的; 它允許我上傳一組圖像,並讓客户端可視化發生了什麼。
但是,我發現一些不理想的東西。當您上傳標題圖像然後裁剪時,您在原始圖像上設置的”meta data”(即名稱,描述等) 不會轉移到新裁剪的圖像 (與原始圖像分開保存) 。這給人的印象是,當您添加標題圖像時,”meta data” 未保存。然後更新”meta data” 的唯一方法是轉到媒體庫,並從那裏進行編輯。你可以看到,它不是一個非常直觀的 UX,可能會導致混亂。
我可以想到的最好的解決方案是以某種方式掛鈎到 WordPress 事件中,並將原始圖像中的”meta data” 傳輸到裁剪的圖像。儘管我可以告訴你,沒有辦法做到這一點,所以我想聽聽你的想法。
我對所有的想法和解決方案都開放。
這是對我正在描述的更直觀的表示:
最佳解決方案
這是一個想法,可能需要進一步測試:
/**
* Cropped header image with the same description/caption as the original image
*/
add_filter( 'wp_create_file_in_uploads', function( $cropped, $attachment_id )
{
add_filter( 'wp_insert_attachment_data', function( $data ) use ( $attachment_id)
{
if( doing_action( 'wp_ajax_custom-header-crop' ) && is_array( $data ) )
{
// Copy the original description to the cropped image
$data['post_content'] = get_post_field( 'post_content', $attachment_id, 'db' );
// Copy the original caption to the cropped image
$data['post_excerpt'] = get_post_field( 'post_excerpt', $attachment_id, 'db' );
}
return $data;
} );
return $cropped;
}, 10, 2 );
這裏我們通過 wp_create_file_in_uploads
和 wp_insert_attachment_data
濾鏡從原始圖像複製 description
和 caption
。要限制它在自定義標題 ajax 裁剪的上下文中,我們檢查它:
doing_action('wp_ajax_custom-header-crop')`
在這裏,我們還將原始圖像的 $attachment_id
傳遞給使用 use 關鍵字的關閉。
如果我們需要複製圖像元素,那麼我們可以通過 wp_header_image_attachment_metadata
過濾器使用類似的方法:
/**
* Cropped header image with the same image meta as the original one
*/
add_filter( 'wp_create_file_in_uploads', function( $cropped, $attachment_id )
{
add_filter( 'wp_header_image_attachment_metadata', function( $metadata ) use ( $attachment_id )
{
if( doing_action( 'wp_ajax_custom-header-crop' ) && isset( $metadata['image_meta'] ) )
{
// Fetch the image meta of the original image
$original_metadata = wp_get_attachment_metadata( $attachment_id );
// Copy the original image meta data for the cropped image
if( is_array( $original_metadata['image_meta'] ) )
$metadata['image_meta'] = $original_metadata['image_meta'];
}
return $metadata;
} );
return $cropped;
}, 10, 2 );
希望可以根據您的需要進行調整。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。