天天看點

WordPress從文章中擷取第一張圖檔作為縮略圖

假設您想使用WordPress 的縮略圖功能,但有一個完整的文章需要花費太多時間才能完成。對于新文章,可以是特定的,并按預期使用該功能。對于舊文章,隻想使用它在内容中找到第一個圖像作為縮略圖的,或者如果不存在則使用預設圖。

将其添加到functions.php或制作功能插件:

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 = $matches[1][0];
 
  if(empty($first_img)) {
    $first_img = "/path/to/default.png";
  }
  return $first_img;
}           

前端循環輸出代碼

if ( get_the_post_thumbnail($post_id) != '' ) {
 
  echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
   the_post_thumbnail();
  echo '</a>';
 
} else {
 
 echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
 echo '<img src="';
 echo catch_that_image();
 echo '" alt="" />';
 echo '</a>';
 
}