Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active April 21, 2022 09:10
Show Gist options
  • Save kjbrum/028ccc3ff718e77f9f78 to your computer and use it in GitHub Desktop.
Save kjbrum/028ccc3ff718e77f9f78 to your computer and use it in GitHub Desktop.
Create an array of an attachment image's data.
<?php
/**
* Create an array of an attachment image's data.
*
* @param int $id The id of the attachment image
* @return array $image An array of all the image data
*/
function wp_get_attachment_image_data( $id=null ) {
$image = array();
// Set $id to the post thumbnail image by default
if ( ! $id ) {
global $post;
$id = get_post_thumbnail_id( $post->ID );
}
// Check if metadata exists
if ( ! empty( $id ) && $meta = get_post( $id ) ) {
$image['href'] = get_permalink( $meta->ID );
$image['url'] = $meta->guid;
$image['title'] = $meta->post_title;
$image['alt'] = ( $alt = get_post_meta( $meta->ID, '_wp_attachment_image_alt', true ) ) ? $alt : $meta->post_title;
$image['caption'] = $meta->post_excerpt;
$image['description'] = $meta->post_content;
// Get all our images sizes
if ( $sizes = get_intermediate_image_sizes() ) {
// Add the full size
array_unshift( $sizes, 'full' );
// Add the available image sizes
foreach ( $sizes as $size ) {
$src = wp_get_attachment_image_src( $id, $size );
$image['sizes'][$size] = $src[0];
$image['sizes'][$size . '-width'] = $src[1];
$image['sizes'][$size . '-height'] = $src[2];
}
} else {
$image['sizes'] = null;
}
return $image;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment