Permanent Tourist

Photography and Multimedia by Mark Howells-Mead

  • Portfolio
  • Blog
  • Links
  • About
  • WordPress function: getting attachment and thumbnail captions for a post

    Geek stuff, Internet | 16th August 2011

    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.

    Add a comment

    I receive an email with your comment as soon as you've added it. If you've not posted a comment before, I'll have to check it before it appears online. Bloody spammers are to blame, sorry!