ottenere immagini allegate a un articolo
Voglio poter utilizzare immagini dalla libreria media in uno slider jQuery nella home page, in modo che sia semplice per altri aggiornare le immagini senza doverle hardcodare. Ho allegato diverse foto a un post e ho provato questo codice:
<?php
// Query per il post contenente le immagini dello slider
$image_query = new WP_Query(array('name'=>'slider-images'));
while ( $image_query->have_posts() ) : $image_query->the_post();
// Ottieni tutti gli allegati del post corrente
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
echo '<li>';
echo '<img src="'.wp_get_attachment_url($attachment->ID).'" />';
echo '</li>';
}
}
endwhile;
wp_reset_postdata();
?>
ma non mostra nulla. C'è qualcosa di sbagliato nel mio codice o esiste un modo più semplice/migliore per raggruppare le immagini invece di inserirle in un post?
MODIFICA: Se utilizzo the_content() nel mio loop $image_query, restituisce le immagini in questo formato:
<p>
<a href="...">
<img src="..." />
</a>
</p>
ma quello che mi serve è qualcosa del tipo:
<li>
<a href="...">
<img src="..." />
</a>
</li>
È meglio utilizzare get_children piuttosto che get_posts. Ecco un rapido esempio funzionante. Si tratta di una funzione che può essere definita nel tuo plugin o nel file functions.php, per poi essere utilizzata come template tag.
/**
* Ottiene tutte le immagini allegate a un post
* @return string
*/
function wpse_get_images() {
global $post;
$id = intval( $post->ID );
$size = 'medium';
$attachments = get_children( array(
'post_parent' => $id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order'
) );
if ( empty( $attachments ) )
return '';
$output = "\n";
/**
* Cicla attraverso ogni allegato
*/
foreach ( $attachments as $id => $attachment ) :
$title = esc_html( $attachment->post_title, 1 );
$img = wp_get_attachment_image_src( $id, $size );
$output .= '<a class="selector thumb" href="' . esc_url( wp_get_attachment_url( $id ) ) . '" title="' . esc_attr( $title ) . '">';
$output .= '<img class="aligncenter" src="' . esc_url( $img[0] ) . '" alt="' . esc_attr( $title ) . '" title="' . esc_attr( $title ) . '" />';
$output .= '</a>';
endforeach;
return $output;
}

devo chiamare questa funzione nel mio loop $image_query? Ho provato ma restituisce solo una stringa vuota
