jrobinsonc
3/2/2015 - 2:33 PM

Wordpress helper: Get image tag.

Wordpress helper: Get image tag.

<?php

/**
* get_thumb_tag
*
* @author JoseRobinson.com
* @link https://gist.github.com/jrobinsonc/3959a3c40138fdb701c8
* @version 201506211936
* @param int $post_id
* @param mixed $size
* @param boolean $caption
* @return string
*/
function get_thumb_tag($post_id, $size, $caption = true)
{
    $thumbnail_id = get_post_thumbnail_id($post_id);

    if ('' === $thumbnail_id)
        return '';

    $image_obj = wp_get_attachment_image_src($thumbnail_id, $size);

    if (false === $image_obj)
        return '';

    $post_info = get_post($thumbnail_id);

    if (null === $post_info)
        return '';

    // $image_obj[1], $image_obj[2]

    $result = sprintf('<figure class="post-media-%s">', $thumbnail_id);
    $result .= sprintf('<img src="%s" alt="%s" />', $image_obj[0], esc_attr($post_info->post_excerpt));

    if (true === $caption)
    {
        if ($post_info->post_content !== '')
            $result .= sprintf('<p>“%s”</p>', $post_info->post_content);

        if ($post_info->post_excerpt !== '')
            $result .= sprintf('<figcaption>%s</figcaption>', $post_info->post_excerpt);
    }

    $result .= sprintf('</figure>');

    return $result;
}