小冬SEO

wordpress调用文章内的第一张图片

2019-03-17 10:32:25 1778 WordPress笔记

有时候我们需要获取到文章的第一张图片,但是在实际运用中,我们的图片标签外可能包裹了其他标签,这个时候系统会自动过滤掉。
但是我们的需求是就是文章中第一张图片,不用过滤掉,一下代码就能实现:

fuction.php里面添加函数

function get_content_first_image($content){

if ( $content === false ) $content = get_the_content();

preg_match_all('|<img.*?src=['"](.*?)['"].*?>|i', $content, $images);

if($images){

return $images[1][0];

}else{

return false;

}

}

调用标签为:

<img  src="<?php echo get_content_first_image(get_the_content()); ?>" alt="<?php the_title_attribute(); ?>" >

版权保护: 本文由小冬SEO编辑发布,转载请保留链接: http://www.myseoyh.cn/shuo/120.html