Contrariamente a quanto si creda comunemente, WordPress considera gli allegati come post. Questo è anche il caso delle immagini.
La didascalia di un'immagine corrisponde alla proprietà post_excerpt
dell'oggetto post ottenuto a partire dall'ID dell'immagine:
$image_id = 7;
$image_post = get_post( $image_id );
$caption = $image_post->post_excerpt;
echo $caption;
In pratica la chiave di tutto è ottenere l'ID dell'immagine. Per le immagini in evidenza è semplice:
while( have_posts() ) {
the_post();
if( has_post_thumbnail() ) {
$image_id = get_post_thumbnail_id();
$image_post = get_post( $image_id );
$caption = $image_post->post_excerpt;
echo $caption;
}
}
In alternativa dobbiamo creare un Loop di allegati:
while( have_posts() ) {
the_post();
$id = get_the_ID();
$args = array(
'post_parent' => $id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image'
);
$images = get_children( $args );
if( $images ) {
foreach( $images as $attachment_id => $image ) {
// $image è già un oggetto, quindi:
$caption = $image->post_excerpt;
echo $caption;
}
}
}