WordPress获取文章中第一张图片

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;
}

/path/to/default.png是当文章中没有图片的时候,代替的图片,可以自己更换。

一般获取文章中第一张图片会作为缩图使用,此方案通常配合WordPress特色图像方案来完成。下面是一个在 the_loop 中使用的方法。

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>';

}

参考资料:
https://developer.wordpress.org/reference/functions/the_post_thumbnail/
https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/
https://developer.wordpress.org/reference/functions/has_post_thumbnail/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注