如何給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上傳到服務器后即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM