data_get-attachment-image-url.js
/**
* @module getAttachmentImageUrl
* @description Get an image URL from a WordPress attachment object for a specific size.
*
* @since 4.0.3
*
* @param {object} attachment - The WordPress attachment object
* @param {string} size - The desired image size (e.g., 'thumbnail', 'medium', 'full')
* @param {string} [fallbackSize] - The fallback size if the requested size isn't available
*
* @return {string} The URL of the requested image size, or the fallback size, or the base URL.
* @example
* import { getAttachmentImageUrl } from '@gravityforms/utils';
*
* const attachment = {
* id: 123,
* url: 'https://example.com/image.jpg',
* sizes: {
* thumbnail: {
* url: 'https://example.com/image-thumbnail.jpg',
* },
* medium: {
* url: 'https://example.com/image-medium.jpg',
* },
* },
* };
*
* const imageUrl = getAttachmentImageUrl( attachment, 'thumbnail' );
* console.log( imageUrl ); // 'https://example.com/image-thumbnail.jpg'
*/
export const getAttachmentImageUrl = ( attachment, size, fallbackSize = 'full' ) => {
// Guard clauses for invalid inputs
if ( ! attachment || typeof attachment !== 'object' ) {
console.warn( 'Invalid attachment object provided' );
return '';
}
// If no size specified, use fallbackSize
const requestedSize = size || fallbackSize;
// Check if the requested size exists in sizes object
if (
attachment.sizes &&
attachment.sizes[ requestedSize ] &&
attachment.sizes[ requestedSize ].url
) {
return attachment.sizes[ requestedSize ].url;
}
// Fallback to specified fallbackSize if different from requested size
if (
requestedSize !== fallbackSize &&
attachment.sizes &&
attachment.sizes[ fallbackSize ] &&
attachment.sizes[ fallbackSize ].url
) {
return attachment.sizes[ fallbackSize ].url;
}
// Final fallback to base url
return attachment.url || '';
};
export default getAttachmentImageUrl;