记录一些常用的函数和瞎折腾的过程……

wordpress函数之:自动缩略图(2)

提醒:本文最后更新于 2376 天前,文中所描述的信息可能已发生改变,请谨慎使用。

下面这个函数也是获取文章中的图片作为缩略图的方法,文章中有图片,则提取作为缩略图,没有的话,随机输出定义好的图片。仅供参考:

//获取文章第一张图片
function get_content_first_image($content){
    if ( $content === false ) $content = get_the_content();
    preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $images, PREG_PATTERN_ORDER);
    if(count($images[1]) > 0){
        $first_img =  $images[1][0];
        echo '<img src="'.$first_img.'" />';
    }
    else{
        echo '<img src="/images/'.mt_rand(1,20).'.jpg">';
    }
}

在列表页面需要调用的缩略图的地方插入以下代码即可:

<?php get_content_first_image(get_the_content()); ?>