It’s rare that I post anything heavily internet-related or even extremely code-geeky, so please skip this entry if it’s of no interest! I was asked today if I knew how to get the captions of Post attachments in WordPress and so I knocked up the following two functions; one which returns an array of all captions assigned to media files attached to the Post, and one which returns the caption of the image assigned to the Post as the post thumbnail. Add the following functions to the functions.php file in your WordPress theme.
function getThumbnailCaption($postID=0){ // return caption of post thumbnail if(!$postID){ global $post; $postID = $post->ID; } $returnArray=array(); if(has_post_thumbnail($postID)){ $thumb_id = get_post_thumbnail_id($postID); $args = array( 'post_type' => 'attachment', 'post_parent' => $postID, 'include' => $thumb_id ); $thumb_images = get_posts($args); foreach ($thumb_images as $thumb_image) { $returnArray[] = $thumb_image->post_excerpt; } } return $returnArray[0]; }//getThumbnailCaption function getAttachmentCaptions($postID=0){ // return array containing all captions if(!$postID){ global $post; $postID = $post->ID; } $returnArray=array(); $args = array( 'post_type' => 'attachment', 'post_parent' => $postID, ); $thumb_images = get_posts($args); foreach ($thumb_images as $thumb_image) { $returnArray[] = $thumb_image->post_excerpt; } return $returnArray; }// getAttachmentCaptions
Any questions? Leave a comment here so that future readers can follow.
Leave a Reply