WordPress 從 2.9 版開始支持文章特色圖像功能,使用 WordPress 的特色圖像功能,會使用網站更加規範,提高頁面加載速度,如何讓主題支持特色圖像功能很簡單。
第一步,添加主題對特色圖像功能的支持
將下面代碼主題 functions.php 文件中:
// 添加特色圖像功能
add_theme_support('post-thumbnails');
set_post_thumbnail_size(130, 100, true); // 圖片寬度與高度
其中圖片的長寬可以自行修改。
第二步,添加特色圖像調用代碼
將下面的代碼添加到主題模板的適當位置,比如分類歸檔模板 archive.php 主循中:
<?php
if (has_post_thumbnail()) {
     // 顯示特色圖像
     the_post_thumbnail();
} else {
     // 設置特色圖像
     $attachments = get_posts(array(
          'post_type' => 'attachment',
          'post_mime_type'=>'image',
          'posts_per_page' => 0,
          'post_parent' => $post->ID,
          'order'=>'ASC'
     ));
     if ($attachments) {
          foreach ($attachments as $attachment) {
               set_post_thumbnail($post->ID, $attachment->ID);
               break;
          }
          // 顯示特色圖像
          the_post_thumbnail();
     }
} ?>
代碼説明,如果未手動設置特色圖像,那麼會自動調用第一個圖片附件的 「縮略圖」 作為特色圖像,並顯示它。
注:代碼中所使用的 WP 函數:
has_post_thumbnail()
set_post_thumbnail()
the_post_thumbnail()
可以到官方 Codex 查看詳細使用説明,並根據需要加以修改。
調用顯示特色圖像還可以使用另一種方法:
如果你認為將特色圖像調用代碼加到主題模板主循環中看上去會很亂,可以將下面的代碼添加到主題 functions.php 文件中:
// 特色圖像
add_filter('the_content', 'set_featured_image_from_attachment');
function set_featured_image_from_attachment($content) {
     global $post;
     if (has_post_thumbnail()) {
          // 顯示特色圖像
          $content = the_post_thumbnail() . $content;
     } else {
          // 獲取和設置特色圖像
          $attachments = get_children(array(
               'post_parent' => $post->ID,
               'post_status' => 'inherit',
               'post_type' => 'attachment',
               'post_mime_type' => 'image',
               'order' => 'ASC',
               'orderby' => 'menu_order'
          ));
          if ($attachments) {
               foreach ($attachments as $attachment) {
                    set_post_thumbnail($post->ID, $attachment->ID);
                    break;
               }
               // 顯示特色圖像
               $content = the_post_thumbnail() . $content;
          }
     }
     return $content;
}
這段代碼基本原理與上面的相同 , 除了使用 get_children 過濾 the_content(),而不是 get_posts() 。