Created
August 31, 2017 20:14
-
-
Save HowdyMcGee/70e6df1c9979aa38ef386c3cde81a709 to your computer and use it in GitHub Desktop.
Return a Custom Image Array Attached to Given Post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generate a custom array of image attachment information | |
* | |
* @param Integer $post_id | |
* | |
* @return Array( | |
* 'ID' => 123, | |
* 'title' => 'Image Title Attribute', | |
* 'alt' => 'Image Alt Attribute', | |
* 'caption' => 'Image Caption Attribute', | |
* 'description' => 'Image Description Attribute', | |
* 'page_url' => 'http://wp.example.net/path_to_post/post_name/attachment_name' | |
* 'sizes' => Array( | |
* 'thumbnail' => Array( | |
* 'url' => 'http://wp.example.net/wp-content/uploads/current_year/publish_month/filename-150x150.jpg', | |
* 'width' => 150, | |
* 'height' => 150, | |
* 'intermediate' => 1, | |
* ) | |
* ) | |
* ) | |
*/ | |
function wpse_get_custom_image_data( $post_id = false ) { | |
if( empty( $post_id ) ) { | |
return array(); | |
} | |
$attachments = array(); | |
$image_arr = get_posts( array( | |
'post_type' => 'attachment', | |
'posts_per_page' => 500, | |
'post_status' => 'any', | |
'post_parent' => $post_id, | |
'post_mime_type' => array( 'image/jpeg', 'image/gif', 'image/png' ), | |
) ); | |
if( ! empty( $image_arr ) ) { | |
foreach( $image_arr as $postobj ) { | |
$image_sizes = array( 'thumbnail', 'medium', 'large', 'full' ); | |
$alt_attr = get_post_meta( $postobj->ID, '_wp_attachment_image_alt', true ); | |
$image_data = array( | |
'ID' => $postobj->ID, // Image ID | |
'title' => $postobj->post_title, // Image Title | |
'alt' => $alt_attr, // Image Alt Attribute | |
'caption' => wp_get_attachment_caption( $postobj->ID ), // Image Caption | |
'description' => $postobj->post_content, // Image Description | |
'page_url' => get_permalink( $postobj->ID ), // Attachment Page Permalink | |
); | |
foreach( $image_sizes as $size ) { | |
$src_arr = wp_get_attachment_image_src( $postobj->ID, $size, false ); | |
if( ! empty( $src_arr ) ) { | |
// Reassign keys | |
$new_src_arr = array_combine( array( 'url', 'width', 'height', 'intermediate' ), array_values( $src_arr ) ); | |
$image_data['sizes'][ $size ] = $new_src_arr; | |
} | |
} | |
$attachments[] = $image_data; | |
} | |
} | |
return $attachments; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment