How to show description under an inserted image?

I’m using wordpress’ native media manager. I have a problem. I can show the title under the image. But I want also to show the description. Is it possible to do?

3 s
3

This is actually quite easy: You just hijack the short code handler for image captions, grab the post_content (the image description) and set its content as a value for the attribute caption. Then you call the original shortcode handler.

The following example requires the shortcode attribute desc set to 1 to make the magic work:

<?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:      Thomas Scholz <info@toscho.de>
 * Author URI:  http://toscho.de
 * 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 '';
}

Now you add a description …

enter image description here

… use regular caption markup …

enter image description here

… and get the description nicely formatted:

enter image description here

If you add the parameter desc with a value different from 1 to the caption (desc=0 for example) no description will be used.

Download on GitHub.

Leave a Comment