wordpress從2.9版開始支持文章特色圖像功能,使用wordpress的特色圖像功能,會(huì)使用網(wǎng)站更加規(guī)范,提高頁(yè)面加載速度,如何讓主題支持特色圖像功能很簡(jiǎn)單。
第一步,添加主題對(duì)特色圖像功能的支持
將下面代碼主題 functions.php 文件中:
// 添加特色圖像功能
add_theme_support('post-thumbnails');
set_post_thumbnail_size(130, 100, true); // 圖片寬度與高度
其中圖片的長(zhǎng)寬可以自行修改。
第二步,添加特色圖像調(diào)用代碼
將下面的代碼添加到主題模板的適當(dāng)位置,比如分類歸檔模板archive.php主循中:
<?php
if (has_post_thumbnail()) {
// 顯示特色圖像
the_post_thumbnail();
} else {
// 設(shè)置特色圖像
$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();
}
} ?>
代碼說(shuō)明,如果未手動(dòng)設(shè)置特色圖像,那么會(huì)自動(dòng)調(diào)用第一個(gè)圖片附件的“縮略圖”作為特色圖像,并顯示它。
注:代碼中所使用的WP函數(shù):
has_post_thumbnail()
set_post_thumbnail()
the_post_thumbnail()
可以到官方Codex查看詳細(xì)使用說(shuō)明,并根據(jù)需要加以修改。
調(diào)用顯示特色圖像還可以使用另一種方法:
如果你認(rèn)為將特色圖像調(diào)用代碼加到主題模板主循環(huán)中看上去會(huì)很亂,可以將下面的代碼添加到主題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 {
// 獲取和設(shè)置特色圖像
$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過(guò)濾the_content(),而不是get_posts()。
新聞熱點(diǎn)
疑難解答
圖片精選