wordpress功能集成(十二):调用文章内容中的图片

给自己的主题分类页面文章列表添加一个缩略图,可以调用文章内容中的图片。不过我觉得调用文章内容中的图片更广泛的应用应该是图片(相册)主题。

将文章内容中的图片取出来原理很简单,用正则表达式从文章内容中匹配图片代码即可,示例代码:

  1. <?php   
  2. //获取缩略图   
  3. function get_post_img($width="100",$height="100") {   
  4.     //申明全局变量   
  5.     global $post;   
  6.        
  7.     $first_img = '';   
  8.     //从文章内容中匹配图片代码   
  9.     $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  10.     //要返回的代码$matches[1][0]为匹配的第一个图片代码  
  11.     $first_img = '<img src="'. $matches[1][0] .'" width="'.$width.'" height="'.$height.'" alt="'.$post->post_title .'"/>';  
  12.     //如果没有图片,返回默认图片的代码  
  13.     if(empty($matches[1][0])){  
  14.         $first_img = '<img src="'. get_bloginfo('template_url') .'/images/defalt.png" alt="'.$post->post_title .'" width="'.$width.'" height="'.$height.'"/>';   
  15.     }   
  16.        
  17.     return $first_img;   
  18. }   
  19. ?>  

这里返回了一个图片代码。

猫10有个非常炫的图片主题,这个主题就是从文章内容中将图片挑选出来,使用的部分代码如下:

  1. <?php    
  2. $pc = $post->post_content;    
  3. $sp = '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i'; 
  4. preg_match_all( $sp, $pc, $aPics );   
  5. $np = count($aPics[0]);  
  6. if ( $np > 0 ) {    
  7.     for ( $i=0; $i < $np ; $i++ ) {   
  8.         echo '<img src="'.$aPics[1][$i].'" alt="'.$aPics[1][$i].'"/>';    
  9.     };    
  10. };   
  11. ?>  

 

已有1条评论

jimier进行回复 取消回复