您现在的位置是:首页 > 文章详情

WordPress从文章中获取第一张图片作为缩略图

日期:2020-03-26点击:505

假设您想使用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>'; }
原文链接:https://yq.aliyun.com/articles/751726
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章