如何给wordpress首页自动显示文章内容的第一个图片

敏捷个人手机应用中使用到的数据来源于wordpress中,因为自己写的页面,所以可以自己写代码获取文章内容的第一个图片作为文章缩略图来显示,这样用户看到首页时图文并茂,感觉会好一些。

现在后台简单的使用PHP编写,使用正则表达式获取第一个图片地址

    //格式化博客列表内容
    private function formatIndexContent($blogs) {
        //strip $rs content
        foreach ($blogs as $blog) {
            preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $blog->post_content, $images);
            $match = $images[1];
            if (count($match) == 0) {
                $blog->pic = "";
            }
            else {
                $blog->pic = $match[0];     
            }
            $blog->post_content = mb_substr(strip_tags($blog->post_content), 0, 140) . "...";
        }
        return json_encode($blogs);
    }

敏捷个人网站使用的是自带的主题 Twenty Eleven Theme,之前也想把网页上wordpress首页自动显示一下缩略图,不过查找了一下网络,找到一个插件,用了一下发现这个插件的机制是生成一张缩略图,而我不希望它在我服务器上生成图片,我只是想要自动显示第一张图片作为缩略图而已。没改之前是这样的显示页面,看起来是不是觉得单调呢?

想改了好几次,今天决定改掉它,结果现在如下,是不是看了起来舒服多了啊。

下面我简单说一下,如何修改wordpress的php带来来实现这个首页自动显示文章内容缩略图的功能。

  1. 找到主题下的functions.php,增加一个现实第一个图片的方法。我是用的是 twentyeleven 主题,所以修改文件存在于 wp-content/themes/twentyeleven/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 = bloginfo('template_url'). '/images/default-thumb.jpg'; 
        } 
        return $first_img; 
     } 
  2. 首页是index.php生成的,我们能看到以下代码,
        <?php get_template_part( 'content', get_post_format() ); ?>

    说明是根据文章类型来生成的内容,不同文章类型的内容生成文件一般是content*.php的文件

    我的文章之前都是用相册类型编写的,所以我只需要修改 content-gallery.php文件即可。找到 <div class="entry-content">,在后面添加显示图片的代码即可
    <div class="entry-content">
                <a href="<?php the_permalink(); ?>"><img src="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>"/></a>  //增加这一行即可
                <?php if ( post_password_required() ) : ?>
  3. 修改后,把functions.php和 content-gallery.php上传到服务器后即可

posted on 2014-10-17 09:44  周 金根  阅读(11331)  评论(0编辑  收藏  举报

导航