2010-02-19 76 views
1

我想從the_content()中提取圖像,並希望顯示index.php文章中的第一張圖像,並希望在single.php中顯示所有圖像。要做到這一點,我申請上the_content過濾器():從內容中提取圖像

<?php 
/***************************************************************************** 
    Post Summary Filter - Grap Image Thumbnails, Strip Tags, etc 
******************************************************************************/ 
add_filter('the_content', 'filterContentSummary', 0); 

function filterContentSummary($content){ 
    global $post; 

    if(is_home() || is_category() || is_tag() || is_author() || is_date() || is_search() || is_single){ 
     //if NOT single page or "page" page 
      $img='';  //default img code 
      $final_width = 300; 

      $content = $post->post_content; 

      //search for first image in article 
      preg_match('/<img[^>]*>/i',$content,$matches); 

      //image found, process it 
      if($matches){ 
       preg_match('/src="[^"]*"/i',$matches[0],$src); 
       preg_match('/width="(\d*)[^"]*"/i',$matches[0],$width); 

       if($width[1] < $final_width){ 
        $final_width = $width[1]; 
       } 


      } 

      //prepare text 
      if(!empty($post->post_excerpt)){ 
       $content = $post->post_excerpt; 
      }else{ 
       //strip shortcodes, tags 
       $content = preg_replace('/\[\/*[^\]]*\]/i', '', $content); //cont is ready 
       $content = preg_replace('/<[^>]*>/i', '', $content); //cont is ready 
       $content = substr($content,0,500); 
       $content = explode(". ", $content); 

       array_pop($content); 
       $content = implode(". ", $content) . ""; 
      } 

      if($content=="."){ 
       $content = $post->post_content; 
      } 
      //prepare final content 
      $content = "<p>". $content ."</p>"; 

      //Adding Read more link 
      $content .= "<p align='right' class='seemore'><a href=". get_permalink() . "></a></p>"; 
    } 
    // Make sure to return the content 
    return $content; 
} 
?> 

使用的index.php正則表達式我從後找到的第一個圖像,並顯示它:

<?php while (have_posts()) : the_post(); 
          $content = $post->post_content; 
          preg_match_all('/(<img.*src="(.*)"[^>]*>)/iU',$content,$matches); 
         ?> 

現在$matches擁有所有的圖片:

<div class="content-img"><img src="<?php echo $matches[2][0];?>"/></div> 

...用於在帖子上顯示第一張圖片。

但我怎麼能顯示single.php上的所有圖像?

回答

3

global $post之後只需加if(is_single()) return $content;這樣如果是單一模板你過濾器會返回原始內容與所有圖像......然後正常顯示。