2012-07-26 41 views
0

我經常使用這個功能來提取後的圖像:WP/PHP函數來提取圖像不起作用

function first_post_image($content) { 
$first_img = ''; 
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches); 
$first_img = $matches [1] [0]; 
return $first_img; 
} 

然後我展示用下面的代碼

<?php $postimage = first_post_image(get_the_content()); ?> // catch the image 
<img src="<?php echo $postimage; ?>" /> //view the image 
圖像

現在我嘗試在我的最後一個模板(wp)中使用此功能,但圖像未顯示。我可以看到標籤img和src屬性,但它是空的。

有人可以幫助我嗎?謝謝

回答

0

你做了var_dump($postimage);看看函數返回什麼?

這是一個工作,而不是返回一個空數組,如果沒有圖像它將返回false,所以你可以指定一個備份或默認圖像。

/** 
    * Extracts the first image in the post content 
    * 
    * @param object $post the post object 
    * @return bool|string false if no images or img src 
    */ 
    function extract_image($post) { 
     $html = $post->post_content; 
     if (stripos($html, '<img') !== false) { 
      $regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im'; 
      preg_match($regex, $html, $matches); 
      unset($regex); 
      unset($html); 
      if (is_array($matches) && ! empty($matches)) { 
       return $matches[2]; 

      } else { 
       return false; 
      } 
     } else { 
      return false; 
     } 
    } 
0

我做了一些測試,最後我解決了這個問題。我不知道我是否犯了一個錯誤,但代碼是相同的,現在可以正常工作。 謝謝。