| 1 |
/** |
| 2 |
* Attachment utility functions |
| 3 |
* Handles conversion between attachment IDs and URLs |
| 4 |
*/ |
| 5 |
|
| 6 |
/** |
| 7 |
* Get image URL from attachment ID |
| 8 |
* @param attachmentId - WordPress attachment ID |
| 9 |
* @returns Image URL or null if invalid |
| 10 |
*/ |
| 11 |
export const getAttachmentUrl = ( |
| 12 |
attachmentId: string | number | null | undefined, |
| 13 |
): string | null => { |
| 14 |
if (!attachmentId) return null; |
| 15 |
|
| 16 |
const id = String(attachmentId); |
| 17 |
|
| 18 |
// If it's already a URL (for backward compatibility), return it |
| 19 |
if (id.startsWith("http://") || id.startsWith("https://")) { |
| 20 |
return id; |
| 21 |
} |
| 22 |
|
| 23 |
// If it's a numeric attachment ID, use wp_get_attachment_image_url |
| 24 |
// This will be handled by the backend API |
| 25 |
// For frontend, we'll use a REST API endpoint or inline script |
| 26 |
if (/^\d+$/.test(id)) { |
| 27 |
// Use WordPress REST API to get attachment URL |
| 28 |
// For now, return null and let the backend handle it |
| 29 |
// The backend should convert attachment IDs to URLs |
| 30 |
return null; |
| 31 |
} |
| 32 |
|
| 33 |
return null; |
| 34 |
}; |
| 35 |
|
| 36 |
/** |
| 37 |
* Check if a value is an attachment ID (numeric string) |
| 38 |
*/ |
| 39 |
export const isAttachmentId = (value: string | null | undefined): boolean => { |
| 40 |
if (!value) return false; |
| 41 |
return /^\d+$/.test(String(value)); |
| 42 |
}; |
| 43 |
|
| 44 |
/** |
| 45 |
* Check if a value is a URL |
| 46 |
*/ |
| 47 |
export const isUrl = (value: string | null | undefined): boolean => { |
| 48 |
if (!value) return false; |
| 49 |
return value.startsWith("http://") || value.startsWith("https://"); |
| 50 |
}; |
| 51 |
|