wordpress获取文章第一章图片为缩略图的方法

引言:此文由子域名转移而来,因为细微强迫症和放弃子域名而不舍得完全丢弃,所以将会逐步第二次转移文章到主域名上来,二者主题(阿里白秀和D8)均来自大前端,追求完美的同时有一丝小懒,主题就不换了,D8主题用起来挺好。

前面介绍了wordpress如何获取文章所有图片的方法,同理,获取文章第一章图片也很简单,获取之后在文章页面调用即可。只是多了一步,需要判断第一章是特色图像还是文章中的图片(img标签),以至文章中根本没有图片。下面就全面介绍这个方法。

同样,将以下代码插入到functions.php中即可。

  1. //获取文章第一张图片,如果没有图就会显示默认的图或不显示图
  2. function catch_that_image() {
  3.     $specialthumb = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()) );
  4.     global $post, $posts;
  5.     $first_img = '';
  6.     ob_start();
  7.     ob_end_clean();
  8.     $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
  9.     $first_img = $matches [1] [0];
  10.     if($specialthumb){
  11.         $first_img='<img width=100 height=100 border="0" src="' . $specialthumb[0] . '" />';
  12.     }elseif($first_img){  
  13.         $first_img = '<img width=100 height=100 src="'.$first_img.'"/>';
  14.     }else{
  15.         //$first_img = '<img width=100 height=100 src="'.get_bloginfo('template_directory'). '/images/default-thumb.jpg'.'"/>';
  16.     }
  17.     return $first_img;
  18. }

调用的时候,直接调用该函数即可,因为该函数就是返回的img标签,如果想给图片加css样式,可以加载img标签上或者外围的div或者其他标签上,这个就看自己需要了。

发表回复