lug 09

WordPress : isolare la prima immagine di un post e ridimensionarla

  1. function get_first_image($maxwidth,$maxheight,$autoresize=false){
  2.  
  3.         global $post, $posts;
  4.         ob_start();
  5.         ob_end_clean();
  6.         preg_match_all(‘//i’, $post->post_content, $matches);
  7.  
  8.     $first_img = $matches[1][0];
  9.  
  10.     if(!empty($first_img)){
  11.  
  12.     if($autoresize==1){
  13.  
  14.     list($width, $height) = getimagesize($first_img);
  15.  
  16.     if($width>$height){
  17.         if($maxwidth>$width){
  18.             $newwidth = $width;
  19.         }else{
  20.             $newwidth = $maxwidth;
  21.         }
  22.  
  23.         $newheight = ($height*$newwidth)/$width;
  24.  
  25.     }else{
  26.         if($maxheight>$height){
  27.             $newheight = $height;
  28.         }else{
  29.             $newheight = $maxheight;
  30.         }
  31.  
  32.         $newwidth = ($width*$newheight)/$height;
  33.     }
  34.     }else{
  35.  
  36.         $newwidth = $maxwidth;
  37.         $newheight = $maxheight;
  38.  
  39.     }
  40.  
  41.     return "<img src="".$first_img."" alt="".$post->post_title."" width="".$newwidth."" height="".$newheight."" />";
  42.  
  43.     }
  44.  
  45. }

Questa interessante funzione ci permette di prelevare la prima immagine di un post wordpress e ridimensionarla a nostro piacimento.
Utile se si vuole realizzare un template orginale al 100%.

Per utilizzarla dovete inserirla nella pagina functions.php del vostro template prima dell’ultima funzione presente.
La sintassi è la seguente : echo get_first_image(width,height,resize_auto); ?>

Resize_auto è un parametro che se impostato su true dice di ridimensionare l’immagine dinamicamente .
Width e height sono la larghezza e l’altezza massima dell’immagine .

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Che cosa ne pensi?! Lascia un commento!