Come mostrare la descrizione sotto un'immagine inserita?

5 apr 2012, 20:34:44
Visualizzazioni: 25.1K
Voti: 5

Sto utilizzando il gestore dei media nativo di WordPress. Ho un problema: riesco a mostrare il titolo sotto l'immagine, ma vorrei mostrare anche la descrizione. È possibile farlo?

2
Commenti

Come stai definendo la descrizione? Contenuto del post? Estratto del post? Meta personalizzato del post?

Chip Bennett Chip Bennett
5 apr 2012 20:42:01

<textarea id="attachments[706][post_content]" name="attachments[706][post_content]" style=""></textarea>

SNaRe SNaRe
5 apr 2012 20:49:37
Tutte le risposte alla domanda 3
0

In realtà è piuttosto semplice: basta intercettare il gestore degli shortcode per le didascalie delle immagini, prendere il post_content (la descrizione dell'immagine) e impostarlo come valore per l'attributo caption. Poi si richiama il gestore originale dello shortcode.

Il seguente esempio richiede che l'attributo dello shortcode desc sia impostato a 1 per far funzionare la magia:

<?php # -*- coding: utf-8 -*-
/**
 * Plugin Name: T5 Caption With Description
 * Description: Aggiunge la descrizione alle immagini con didascalia se imposti <code>desc=1</code> nello 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';

// Intercetta i gestori nativi degli shortcode.
add_shortcode( 'wp_caption', $callback );
add_shortcode( 'caption',    $callback );

/**
 * Aggiunge la descrizione dell'immagine se necessario
 *
 * @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 );
}

/**
 * Controlla i valori degli attributi richiesti
 *
 * @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 il contenuto del post (la descrizione)
 *
 * @param  string $attachment_id Di solito ha la forma '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 '';
}

Ora aggiungi una descrizione...

inserisci descrizione immagine qui

... usa il markup normale per la didascalia...

inserisci descrizione immagine qui

... e ottieni la descrizione formattata correttamente:

inserisci descrizione immagine qui

Se aggiungi il parametro desc con un valore diverso da 1 alla didascalia (ad esempio desc=0) non verrà utilizzata alcuna descrizione.

Scarica su GitHub.

6 apr 2012 12:53:11
1

Innanzitutto grazie a toscho per la sua soluzione. Nel caso qualcuno avesse bisogno del codice per il suo tema invece di utilizzarlo come plugin, ecco il codice adattato riscritto come singola funzione:

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);
}

Testato con WordPress 4.2.3 e funziona senza problemi.

30 lug 2015 11:48:44
Commenti

come possiamo cambiare il nome della classe del contenitore della descrizione?

Rajneesh Tiwari Rajneesh Tiwari
20 lug 2021 20:00:39
0

Ho trovato la soluzione. Volevo mostrare la descrizione sotto tutte le immagini. Questa soluzione funziona perfettamente. Grazie a https://wordpress.stackexchange.com/users/3687/tom-auger

<?php
/*
Plugin Name: Esempio sostituzione galleria WPSE-45326
Plugin URI: https://wordpress.stackexchange.com/questions/45326
Description: Un plugin per dimostrare come sostituire lo shortcode 'gallery' predefinito e aggiungere tag HTML aggiuntivi per una maggiore personalizzazione.
Version: 1.0
Author: Tom Auger
Author URI: http://www.tomauger.com
License: GPL2
*/

class wpse_45326_Gallery_Replacement {
    function __construct(){
        // Agganciamo all'azione plugins-loaded poiché è il primo hook di azione reale disponibile.
        // Tuttavia, se stai usando un tema e vuoi sostituire il suo shortcode 'gallery' personalizzato,
        // potresti aver bisogno di usare un altro hook. Cerca nei file del tuo tema genitore per 'gallery' e vedi
        // quale hook sta usando per definire il suo shortcode gallery, così puoi assicurarti che questo codice venga eseguito DOPO il loro codice.
        add_action( "init", array( __CLASS__, "init" ) );
    }

    function init(){
        remove_shortcode( 'gallery' ); // Rimuove l'implementazione predefinita dello shortcode gallery
        add_shortcode( 'gallery', array( __CLASS__, "gallery_shortcode" ) ); // E lo sostituisce con il nostro!
    }

    /**
    * Lo shortcode Gallery.
    *
    * Questo è stato preso direttamente da wp-includes/media.php. C'è un sacco di roba buona lì dentro.
    * Tutto quello che vuoi fare è aggiungere un po' più di HTML, e visto che (per qualche motivo) non hanno fornito più
    * filtri per poterlo fare, dobbiamo sostituire completamente lo shortcode Gallery.
    *
    * @param array $attr Attributi dello shortcode.
    * @return string Contenuto HTML per visualizzare la galleria.
    */
    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: Questi sono tutti gli 'opzioni' che puoi passare attraverso la definizione dello shortcode, es: [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'    => '',
            // Ecco le nuove opzioni che abbiamo aggiunto ai valori predefiniti dello 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>
            <!-- vedi gallery_shortcode() in 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}>";

            // MODIFICA: includi l'HTML del titolo e della descrizione se abbiamo fornito i parametri rilevanti nello shortcode (titletag, descriptiontag)
            if ( $captiontag ) {
                $output .= "
                    <{$captiontag} class='wp-caption-text gallery-caption'>";
                // La DIDASCALIA, se presente
                if ( trim( $attachment->post_excerpt ) ) {
                    $output .= "
                        " . wptexturize($attachment->post_excerpt);
                }

                // Il TITOLO, se non abbiamo reso vuoto il parametro 'titletag'
                if ( $titletag ){
                    $output .= "
                        <{$titletag} class=\"gallery-item-title\">" . $attachment->post_title . "</{$titletag}>";
                }

                // La DESCRIZIONE, se non abbiamo specificato un 'descriptiontag' vuoto
                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();
6 apr 2012 20:00:02