Skip to content

Instantly share code, notes, and snippets.

@thefuxia
Last active May 26, 2021 15:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save thefuxia/2318565 to your computer and use it in GitHub Desktop.
Save thefuxia/2318565 to your computer and use it in GitHub Desktop.
T5 Caption With Description
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: T5 Caption With Description
* Description: Adds the description to images with a caption if you set <code>desc=1</code> in the shortcode.
* Version: 2015.03.26
* Author: Fuxia Scholz
* Author URI: https://fuxia.me
* License: MIT
* License URI: http://www.opensource.org/licenses/mit-license.php
*/
namespace T5\Images\Captions;
$callback = __NAMESPACE__ . '\add_description';
// Hijack the native shortcode handlers.
add_shortcode( 'wp_caption', $callback );
add_shortcode( 'caption', $callback );
/**
* Add image description if needed
*
* @param array $attr
* @param null $content
* @return string
*/
function add_description( $attr, $content = null )
{
if ( needs_description( $attr ) )
$attr['caption'] = get_description( $attr['id'] );
return img_caption_shortcode( $attr, $content );
}
/**
* Check required attribute values
*
* @param array $attr
* @return bool
*/
function needs_description( Array $attr ) {
if ( empty ( $attr['desc'] ) )
return FALSE;
if ( 1 > (int) $attr['width'] )
return FALSE;
return ! empty ( $attr['id'] );
}
/**
* Prepare post content (the description)
*
* @param string $attachment_id Usually it looks like 'attachment_123'
* @return string
*/
function get_description( $attachment_id ) {
$post_id = str_replace( 'attachment_', '', $attachment_id );
$img = get_post( (int) $post_id );
if ( is_a( $img, 'WP_Post' ) )
return wpautop( $img->post_content );
return '';
}
@pagol
Copy link

pagol commented Apr 26, 2013

@elphin
Copy link

elphin commented Jun 3, 2020

Hi there,
not sure if someone still read this but in case you do: I have a question.

Your script works great but only if the description field is not empty!
I noticed the caption tag is completely stripped for images without a description.

Is there a workarround?
Thanx!!
Jim

@rajneesh594
Copy link

rajneesh594 commented May 26, 2021

Hi there,
not sure if someone still read this but in case you do: I have a question.

Your script works great but only if the description field is not empty!
I noticed the caption tag is completely stripped for images without a description.

Is there a workarround?
Thanx!!
Jim

how you used the above code, can you please explain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment