2025年02月14日 建站教程
wordpress如何自动获取文章中第一张图片为缩略图,下面web建站小编给大家简单介绍一下具体代码!
1、打开当前主题functions.php文件,新增以下代码:
function wp_content_image() {
global $post;
$content = $post->post_content;
preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
$n = count($strResult[1]);
if($n > 0){
echo '<dt><a href="'.get_permalink().'"><img src="/static'.$strResult[1][0].'" alt="'.trim(strip_tags( $post->post_title )).'"/></a></dt>';
}
}
2、页面中调用代码:
<?php echo wp_content_image(); ?>
本文链接:http://so.lmcjl.com/news/23147/