¿Cómo mostrar la descripción debajo de una imagen insertada?
Estoy usando el gestor de medios nativo de WordPress. Tengo un problema. Puedo mostrar el título debajo de la imagen. Pero también quiero mostrar la descripción. ¿Es posible hacerlo?

Esto es realmente bastante sencillo: Simplemente interceptas el manejador del shortcode para los subtítulos de imágenes, obtienes el post_content
(la descripción de la imagen) y estableces su contenido como valor para el atributo caption
. Luego llamas al manejador original del shortcode.
El siguiente ejemplo requiere que el atributo del shortcode desc
esté configurado como 1
para que funcione la magia:
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: T5 Caption With Description
* Description: Añade la descripción a imágenes con subtítulo si configuras <code>desc=1</code> en el 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';
// Intercepta los manejadores nativos de shortcodes.
add_shortcode( 'wp_caption', $callback );
add_shortcode( 'caption', $callback );
/**
* Añade la descripción de la imagen si es necesario
*
* @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 );
}
/**
* Comprueba los valores de atributo requeridos
*
* @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'] );
}
/**
* Prepara el contenido del post (la descripción)
*
* @param string $attachment_id Normalmente tiene el formato '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 '';
}
Ahora añades una descripción...
... usa el marcado de subtítulo habitual...
... y obtienes la descripción bien formateada:
Si añades el parámetro desc
con un valor diferente a 1
al subtítulo (por ejemplo, desc=0
), no se usará ninguna descripción.

En primer lugar, gracias a toscho por su solución. En caso de que alguien necesite el código para su tema en lugar de usarlo como un plugin, aquí está el código adaptado reescrito como una sola función:
add_shortcode('wp_caption', 'img_caption_add_description');
add_shortcode('caption', 'img_caption_add_description');
function img_caption_add_description($attr, $content = null)
{
$post_id = str_replace('attachment_', '', $attr['id']);
$img = get_post((int)$post_id);
if (is_a($img, 'WP_Post')) {
$attr['caption'] = $img->post_content;
}
return img_caption_shortcode($attr, $content);
}
Probé esto con WordPress 4.2.3 y funciona sin problemas.

Encontré la solución. Quería mostrar la descripción debajo de todas las imágenes. Esta solución funciona genial. Gracias a https://wordpress.stackexchange.com/users/3687/tom-auger
<?php
/*
Plugin Name: Ejemplo de reemplazo de galería WPSE-45326
Plugin URI: https://wordpress.stackexchange.com/questions/45326
Description: Un plugin para demostrar cómo reemplazar el shortcode 'gallery' predeterminado y agregar etiquetas HTML adicionales para mayor personalización.
Version: 1.0
Author: Tom Auger
Author URI: http://www.tomauger.com
License: GPL2
*/
class wpse_45326_Gallery_Replacement {
function __construct(){
// Enganchamos en la acción plugins-loaded ya que es el primer hook de acción real disponible para nosotros.
// Sin embargo, si estás usando un tema y quieres reemplazar el shortcode personalizado 'gallery' de ese tema,
// es posible que necesites usar otra acción. Busca en los archivos de tu tema padre por 'gallery' y revisa
// qué hook está usando para definir su shortcode de galería, para asegurarte de que este código se ejecute DESPUÉS del suyo.
add_action( "init", array( __CLASS__, "init" ) );
}
function init(){
remove_shortcode( 'gallery' ); // Elimina la implementación predeterminada del shortcode de galería
add_shortcode( 'gallery', array( __CLASS__, "gallery_shortcode" ) ); // ¡Y lo reemplazamos con el nuestro!
}
/**
* El shortcode de Galería.
*
* Esto ha sido tomado textualmente de wp-includes/media.php. Hay muchas cosas buenas allí.
* Todo lo que quieres hacer es agregar más HTML, y como (por alguna razón) no proporcionaron más
* filtros para poder agregar, tenemos que reemplazar completamente el shortcode de Galería.
*
* @param array $attr Atributos del shortcode.
* @return string Contenido HTML para mostrar la galería.
*/
function gallery_shortcode($attr) {
global $post;
static $instance = 0;
$instance++;
$output = apply_filters('post_gallery', '', $attr);
if ( $output != '' )
return $output;
if ( isset( $attr['orderby'] ) ) {
$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
if ( !$attr['orderby'] )
unset( $attr['orderby'] );
}
// NOTA: Estos son todos los 'opciones' que puedes pasar a través de la definición del shortcode, ej: [gallery itemtag='p']
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => '',
// Aquí están las nuevas opciones que agregamos a los valores predeterminados del shortcode
'titletag' => 'p',
'descriptiontag' => 'p'
), $attr));
$id = intval($id);
if ( 'RAND' == $order )
$orderby = 'none';
if ( !empty($include) ) {
$include = preg_replace( '/[^0-9,]+/', '', $include );
$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
} elseif ( !empty($exclude) ) {
$exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
} else {
$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
}
if ( empty($attachments) )
return '';
if ( is_feed() ) {
$output = "\n";
foreach ( $attachments as $att_id => $attachment )
$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
return $output;
}
$itemtag = tag_escape($itemtag);
$captiontag = tag_escape($captiontag);
$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';
$selector = "gallery-{$instance}";
$gallery_style = $gallery_div = '';
if ( apply_filters( 'use_default_gallery_style', true ) )
$gallery_style = "
<style type='text/css'>
#{$selector} {
margin: auto;
}
#{$selector} .gallery-item {
float: {$float};
margin-top: 10px;
text-align: center;
width: {$itemwidth}%;
}
#{$selector} img {
border: 2px solid #cfcfcf;
}
#{$selector} .gallery-caption {
margin-left: 0;
}
</style>
<!-- ver gallery_shortcode() en wp-includes/media.php -->";
$size_class = sanitize_html_class( $size );
$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
$output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
$i = 0;
foreach ( $attachments as $id => $attachment ) {
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
$output .= "<{$itemtag} class='gallery-item'>";
$output .= "
<{$icontag} class='gallery-icon'>
$link
</{$icontag}>";
// MODIFICACIÓN: incluir el HTML del título y la descripción si hemos proporcionado los parámetros relevantes del shortcode (titletag, descriptiontag)
if ( $captiontag ) {
$output .= "
<{$captiontag} class='wp-caption-text gallery-caption'>";
// El PIE DE FOTO, si hay uno
if ( trim( $attachment->post_excerpt ) ) {
$output .= "
" . wptexturize($attachment->post_excerpt);
}
// El TÍTULO, si no hemos dejado en blanco el parámetro 'titletag'
if ( $titletag ){
$output .= "
<{$titletag} class=\"gallery-item-title\">" . $attachment->post_title . "</{$titletag}>";
}
// La DESCRIPCIÓN, si no hemos especificado un 'descriptiontag' en blanco
if ( $descriptiontag ){
$output .= "
<{$descriptiontag} class=\"gallery-item-description\">" . wptexturize( $attachment->post_content ) . "</{$descriptiontag}>";
}
$option .= "
</{$captiontag}>";
}
$output .= "</{$itemtag}>";
if ( $columns > 0 && ++$i % $columns == 0 )
$output .= '<br style="clear: both" />';
}
$output .= "
<br style='clear: both;' />
</div>\n";
return $output;
}
}
new wpse_45326_Gallery_Replacement();
