也談WordPress獲取文章首張圖片


從第一次接觸WordPress開始,在前台首頁需要調用文章中的圖片以實現在首頁顯示圖片文章,就看到網絡上流傳甚廣的一個函數:

 

 1 function catch_that_image() {
 2    global $post, $posts;
 3    $first_img = '';
 4    ob_start();
 5    ob_end_clean();
 6    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
 7    $first_img = $matches [1][0];
 8  
 9    if(empty($first_img)){
10    $first_img = "/default.jpg";
11    }
12  return $first_img;
13 }

 

毫無疑問,這個函數是可以正常工作的。但是你知道這個函數會拋出錯誤嗎?當文章沒有圖片,並且PHP和WordPress開啟調試模式時會拋出一個錯誤:”Undefined offset: 0 in ……“

作為一個要求完美的人,當然不希望自己的代碼中有任何錯誤,因此簡單分析解決之。

分析一下這個函數,出錯的原因在於文章沒有圖片時 $matches 將是個空的數組,而第7行:

$first_img = $matches[1][0];

將一個空數組的某個元素賦值給另一個變量,當然就出現錯誤了。由於PHP並不總是以拋出錯誤來解決問題,因此在出錯后 $first_img 並沒有被賦值,后面的代碼也就沒有問題。

明白了這一點,解決起來就很簡單了,直接去判斷數組 $matches 是否為空。

我是這樣處理的:

$first_img = '';
if(empty($matches[1])) $first_img = "/default.jpg";
else $first_img = $matches [1][0];
return $first_img;

就是說,在不明確 $matches是否為空的情況下,不要急於去為 $first_img 賦值。后面的 if 直接去判斷 $matches[1]是否為空。

這樣就避免了一個潛在的錯誤。

完整的修改方案如下:

//獲取文章的第一張圖片地址
function catch_that_image() {
   global $post, $posts;
   $first_img = '';
   ob_start();
   ob_end_clean();
   $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
 
   $first_img = '';
   if(empty($matches[1])) $first_img = "/default.jpg";
   else $first_img = $matches [1][0];
   return $matches[1];
 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM