Skip to content

Instantly share code, notes, and snippets.

@ThomasKujawa
Last active July 4, 2016 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ThomasKujawa/c2d476f73ae977ddcd08 to your computer and use it in GitHub Desktop.
Save ThomasKujawa/c2d476f73ae977ddcd08 to your computer and use it in GitHub Desktop.
Wordpress | Toolbox | Thumbnail with Caption
<?php
/*
Module Name: Thumbnail with caption
Module URI: http://www.transformationpowertools.com/wordpress/wordpress-post-thumbnails-with-caption
Description: show thumbnail with caption, if available, wrapped with '.wp-caption thumb-caption' div; show just the thumbnail otherwise for featured images in the loop [Frontend]
Author: Michael aka alchymyth
Author URI: http://www.transformationpowertools.com/wordpress/author/alchymyth
*/
/* Sicherheitsabfrage */
if ( !class_exists('Toolbox') ) {
die();
}
add_filter('post_thumbnail_html','add_post_thumbnail_caption',10,5);
function add_post_thumbnail_caption($html, $post_id, $post_thumbnail_id, $size, $attr) {
if( $html == '' || !in_the_loop() ) {
return $html;
} else {
$out = '';
$thumbnail_image = get_posts(array('p' => $post_thumbnail_id, 'post_type' => 'attachment'));
if ($thumbnail_image && isset($thumbnail_image[0])) {
$image = wp_get_attachment_image_src($post_thumbnail_id, $size);
$t_width = $image[1] +10; // +10 here for extra padding, needs to be considered in writing css - the default image caption uses +10;
$class = '';
if($attr && isset($attr['class'])) $class = $attr['class'];
if($thumbnail_image[0]->post_excerpt) $out .= '<div class="wp-caption thumb-caption '.$class.'" style="width:'.$t_width.'px; ">';
$out .= $html;
if($thumbnail_image[0]->post_excerpt) $out .= '<p class="wp-caption-text">'.$thumbnail_image[0]->post_excerpt.'</p></div>';
}
return $out;
}
/*css classes for this:
.wp-caption.thumb-caption { ... }
.wp-caption.thumb-caption img { ... }
.wp-caption.thumb-caption .wp-caption-text { ... }
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment