In questo articolo vedremo come creare la struttura HTML per una galleria di immagini da inserire nei vostri post di WordPress. Ovviamente alla galleria andranno aggiunti gli opportuni stili CSS e gli effetti JavaScript. Il codice che presenterò è ampiamente commentato. Vediamone insieme i dettagli.
Come prima cosa, associate ad un post le immagini che desiderate e create una galleria utilizzando le opzioni della Media Library. Quindi aggiungete al file functions.php
il seguente codice:
function my_gallery() {
global $post;
$args = array(
'post_parent' => $post->ID, // Per il post corrente
'post_type' => 'attachment', // Allegati del post
'post_mime_type' => 'image', // Solo le immagini
'order' => 'ASC', // Elenco ascendente
'orderby' => 'menu_order', // Elenco secondo l'ordine del menu
'numberposts' => -1, // Tutti gli allegati
'post_status' => null, // Per tutti i tipi di post
);
// Prendiamo gli allegati con una query
$attachments = get_posts($args);
// Se ci sono allegati, allora:
if ($attachments) {
// Inizializziamo un contatore per controllare l'indice delle immagini
$count = 0;
// Un loop tra le immagini allegate
foreach ($attachments as $attachment) {
// La prima immagine sarà quella centrale grande
if($count == 0) { ?>
< ?php $default_attr = array(
'id' => "test",
'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )),
'title' => trim(strip_tags( $attachment->post_title )),
);
?>
< ?php echo wp_get_attachment_image($attachment->ID, 'full', false, $default_attr); ?>
< ?php echo $attachment->post_title; ?>
< ?php } ?>
-
< ?php if ($count==0) {
// Alla prima thumbnail diamo una classe speciale
$thumb_attr = array(
'class' => "thumb selected",
);
} else {
// Alle altre thumbnail diamo una classe predefinita
$thumb_attr = array(
'class' => "thumb",
);
} ?>
< ?php echo wp_get_attachment_image($attachment->ID, 'thumbnail', false, $thumb_attr); ?>
< ?php $count = $count + 1; } ?>
< ?php }
}
// Creiamo lo shortcode
add_shortcode('my-gallery', 'my_gallery');
?>
Possiamo utilizzare lo shortcode in questo modo:
[my-gallery]