Come ottenere la didascalia di un allegato (get_the_excerpt restituisce l'excerpt del post genitore)?
Sto visualizzando gli allegati nella pagina del post genitore con questo codice:
$args = array('post_type' => 'attachment', 'post_mime_type' => 'image', 'order'=> 'ASC', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
$attachments_url[] = $my_image;
$attachments_caption[] = get_the_excerpt();
}
}
Il problema è che l'excerpt non recupera la didascalia dell'allegato ma l'excerpt del post.
Sai come visualizzare le didascalie degli allegati? grazie
get_the_excerpt()
dovrebbe funzionare correttamente per ottenere la didascalia.
Il tuo problema è che cerca il post da elaborare nelle variabili globali e nel tuo codice non stai impostando queste variabili con gli allegati che stai iterando.
Devi usare setup_postdata()
per farlo funzionare.
Un'altra soluzione potrebbe essere qualcosa come:
get_post_field('post_excerpt', $attachment->ID);

Potresti provare wp_prepare_attachment_for_js( $id )
e ottenere tutto ciò che ti serve per l'allegato.
Riceverai un array con questi elementi:
- id
- title
- filename
- url
- link
- alt
- author
- description
- caption
- name
- status
- uploadedTo
- date
- modified
- menuOrder
- mime
- type
- subtype
- icon
- dateFormatted
- nonces
- editLink
- sizes
- width
- height
- fileLength
- compat
Consulta il Codex: wp_prepare_attachment_for_js()

Questo risolverà il tuo problema
$attachments = attachments_get_attachments(); // Ottieni tutti gli allegati
$total_attachments = count( $attachments ); // Conta il numero totale di allegati
if( $total_attachments ){ // Se ci sono allegati
for( $i=0; $i<$total_attachments; $i++ ){ // Cicla attraverso ogni allegato
echo $attachments[$i]['title']; // Mostra il titolo
echo $attachments[$i]['caption']; // Mostra la didascalia
echo $attachments[$i]['id']; // Mostra l'ID
echo $attachments[$i]['location']; // Mostra la posizione
echo $attachments[$i]['mime']; // Mostra il tipo MIME
echo $attachments[$i]['filesize']; // Mostra la dimensione del file
}
}
