【wordpress教程】如何获取wordpress文章第一张图片并显示

屏聚源码 wordpress教程评论204,187阅读模式

  今天在写wordpress模版的时候碰到一个很头疼的事,那就是如何获取wordpress文章中的第一张图片并显示在首页,列表页等。而且当文章没有图片是要怎么才能显示默认的图片。后来倒腾了好久终于找到代码,只要将如下代码放入主题的functions.php文件中就可以了哦。

  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.   //获取文章中第一张图片的路径并输出

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

  9.   //如果文章无图片,获取自定义图片

  10.   if(emptyempty($first_img)){ //Defines a default image

  11.   echo get_bloginfo ( 'stylesheet_directory' );

  12.   echo '/images/default.jpg';

  13.   //请自行设置一张default.jpg图片

  14.   }

  15.   return $first_img;

  16.   }

  将上方代码放入functions.php文件之后在需要显示图片的地方输出图片:

  1.   <?php echo catch_that_image() ?>

  如果你这样设置了,保证你能顺利打输出图片。下面附上我在网上找到的源码,该源码是有错误的,至于错误在哪需要你们慢慢找出来了。

  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.   //获取文章中第一张图片的路径并输出

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

  9.   //如果文章无图片,获取自定义图片

  10.   if(empty($first_img)){ //Defines a default image

  11.   $first_img = "/images/default.jpg";

  12.   //请自行设置一张default.jpg图片

  13.   }

  14.   return $first_img;

  15.   }

继续阅读
屏聚源码
辅助编程工具通义灵码 你的智能编码助手 屏聚学院

辅助编程工具通义灵码 你的智能编码助手

通义灵码是阿里推出的基于通义大模型,提供代码智能生成、研发智能问答能力的人工智能编码助手,经过海量优秀开源代码数据训练,可根据当前代码文件及跨文件的上下文,为你生成行级/函数级代码、单元测试、代码注释...
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定