WordPress: aggiungere classi CSS dinamiche ai post del Loop

WordPress: aggiungere classi CSS dinamiche ai post del Loop

WordPress aggiunge le classi CSS ai post tramite la funzione (e relativo hook) post_class(). Possiamo sfruttare questa funzionalità per aggiungere delle classi dinamiche in base alla posizione dei post nel Loop. Vediamo come fare.

Aggiungete il seguente codice al file functions.php:


function additional_post_classes( $classes ) {
	global $wp_query;

	if( $wp_query->found_posts < 1 ) {
		return $classes;
	}

	if( $wp_query->current_post == 0 ) {
		$classes[] = 'post-first';
	}

	if( $wp_query->current_post % 2 ) {
		$classes[] = 'post-even';
	} else {
		$classes[] = 'post-odd';
	}

	if( $wp_query->current_post == ( $wp_query->post_count - 1 ) ) {
		$classes[] = 'post-last';
	}

	return $classes;
}
add_filter( 'post_class', 'additional_post_classes' );

Le classi CSS aggiunte sono:

  1. post-first - Primo post nel Loop.
  2. post-even - Post con indice pari.
  3. post-odd - Post con indice dispari.
  4. post-last - Ultimo post nel Loop.
Torna su