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

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

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

在wordpress制作过程中,在首页和分类列表页面可能需要引入缩略图,此时可以用下面的函数读取文章中的第一图当缩略图,若没有,则引入指定的随机缩略图。

//自动缩略图
function catch_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)){ //Defines a default image
        $random = mt_rand(1, 10);
        echo get_bloginfo ( 'stylesheet_directory' );
        echo '/images/random/'.$random.'.jpg';
    }
    return $first_img;
}

在index.php就可以引用了。

<img class="home-thumb" src="<?php echo catch_image(); ?>" />