Elgg 內建模板系統可自動渲染實體圖標,但開發自定義模板時,需手動獲取圖標的 src 地址。本文梳理從上傳、縮圖生成到模板輸出的完整鏈路。
在實體(如 Activity)創建/更新邏輯中,處理 $_FILES['icon']:
if (isset($_FILES['icon']) && substr_count($_FILES['icon']['type'], 'image/')) {
$prefix = "activity/{$activity->guid}";
$filehandler = new ElggFile();
$filehandler->owner_guid = $activity->owner_guid;
$filehandler->setFilename("{$prefix}.jpg");
$filehandler->open('write');
$filehandler->write(get_uploaded_file('icon'));
$filehandler->close();
// 生成多尺寸縮圖
$sizes = ['tiny' => [25,25], 'small' => [40,40], 'medium' => [100,100], 'large' => [200,200]];
foreach ($sizes as $sizeName => [$w, $h]) {
$resized = get_resized_image_from_existing_file($filehandler->getFilenameOnFilestore(), $w, $h, true);
if ($resized) {
$thumb = new ElggFile();
$thumb->owner_guid = $activity->owner_guid;
$thumb->setMimeType('image/jpeg');
$thumb->setFilename("{$prefix}{$sizeName}.jpg");
$thumb->open('write');
$thumb->write($resized);
$thumb->close();
}
}
}
文件最終存儲於 {dataroot}/{owner_guid_last_digits}/ 目錄,文件名為 {guid}{size}.jpg。
在插件 start.php 中註冊:
elgg_register_plugin_hook_handler('entity:icon:url', 'object', 'activity_icon_url_hook');
function activity_icon_url_hook($hook, $type, $returnvalue, $params) {
$entity = $params['entity'];
$size = $params['size'];
if ($entity instanceof Activity) {
return elgg_get_data_url() . "activity/{$entity->guid}{$size}.jpg";
}
return $returnvalue;
}
<img src="<?php echo $activity->getIconURL('medium'); ?>" alt="活動圖標">
getIconURL() 內部觸發 entity:icon:url 鉤子,經過插件處理返回最終 URL。
elgg_get_data_url() 指向 CDN 域名,提升圖片載入速度。