WordPress: usare la prima immagine di un post come thumbnail

WordPress: usare la prima immagine di un post come thumbnail

In un sito in WordPress non sempre viene impostata una thumbnail per ogni post. Per questo motivo spesso è necessario colmare questa lacuna prendendo la prima immagine inserita in un post e usandola come thumbnail. Vediamo come fare.

Inserite il seguente codice nel file functions.php:


function get_first_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches[1][0];

  if(empty($first_img)) {
    $first_img = "/percorso/default.png";
  }
  return $first_img;
}

Quindi inserite la seguente routine nel vostro tema all'interno del Loop:


if ( get_the_post_thumbnail($post_id) != '' ) {

  echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
   the_post_thumbnail();
  echo '</a>';

} else {

 echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
 echo '<img src="';
 echo get_first_image();
 echo '" alt="" />';
 echo '</a>';

}

Ho usato get_the_post_thumbnail() invece che has_post_thumbnail() perchè il suo risultato è più affidabile.

Torna su