Wordpress 非插件實現首頁文章縮略圖
來源:程序員人生 發布時間:2014-01-01 05:22:56 閱讀次數:3910次
一直堅持可以不用插件實現的功能盡量不用插件,即使有些插件功能強大,定制度高,但是越來越多插件會讓網站越來越復雜沉重。
第一步:在functions.php文件里加入一下代碼。
function dp_attachment_image($postid=0, $size='', $attributes='') {
if ($postid<1) $postid = get_the_ID();
if ($images = get_children(array(
'post_parent' => $postid,
'post_type' => 'attachment',
'numberposts' => 1,
'post_mime_type' => 'image',)))
foreach($images as $image) {
$attachment=wp_get_attachment_image_src($image->ID, $size);
?><img src="<?php echo $attachment[0]; ?>" <?php echo $attributes; ?> /><?php
}
}
該代碼為定義一個名為dp_attachment_image()的函數已實現縮略圖功能。其中用$size參數來控制縮略圖大小,該參數有四個值:thumbnail, medium, large,full,從小到大分別對應WordPress里存儲圖像的四個尺寸。
第二步:在index.php中調用dp_attachment_image()函數。一般配合the_excerpt()函數將其放在the_excerpt()函數前面,舉例如下:
<div class="postThumb">
<a href="<?php the_permalink() ?>">
<?php dp_attachment_image($post->ID,'medium', 'alt="' . $post->post_title . '"'); ?>
</a>
</div>
<div class="textPreview">
<?php the_excerpt(); ?>
</div>
其中給定$size的參數為medium,即是將WordPress中縮略圖圖片尺寸為中等尺寸的圖片作為文章縮略圖。
效果如下圖:

總結:
1.用此方法主要是利用WordPress自動生成的縮略圖進行顯示,所以調用函數是不會另外生成縮了圖,節省了空間。但是弊端是縮略圖大小只能用四個參數,所以在用此方法時應該在WordPress后臺媒體庫設置里預先設置好希望顯示的縮略圖尺寸。
2.另外,其實從WordPress2.9開始,就提供了一個the_post_thumbnail()函數來調用當前文章里圖片的縮略圖,只需要在functions.php里加入add_theme_support( ‘post-thumbnails’ );進行聲明即可,用法和上面的方法基本一樣,但是無奈本人用此方法時不顯示縮略圖,至今不知道是什么原因,如有高手懂的麻煩指點下。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈