投稿サムネイルと最新記事5件をindex.phpに掲載させるメモ – wordpress

投稿サムネイルを使って、最新記事と一緒にindex.phpに掲載したい、と色々調べていたところ、なかなかうまいこといくものがなかった。プラグインも嫌だし。
これからのことを考えて、投稿サムネイルを使いたかったわけなんです。

出来たので忘れないようにメモしておきます。


functions.phpに
まずは、2.9から実装された投稿サムネイルの追加を出来るようにします。

add_theme_support( 'post-thumbnails');

この1行を入れてあげることで管理画面下にサムネイルが投稿できるようになります。

さらにfunctions.phpに下記を追加。

function post_thumb() {
$files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
  if($files) :
    $keys = array_reverse(array_keys($files));
    $j=0;
    $num = $keys[$j];
    $image=wp_get_attachment_image($num, 'thumbnail', false);
    $imagepieces = explode('"', $image);
    $imagepath = $imagepieces[1];
    $thumb=wp_get_attachment_image($num, 'thumbnail', false);
    print "$thumb";
  endif;
}

index.phpに

$lastposts = get_posts('numberposts=5');
foreach($lastposts as $post) :
    setup_postdata($post);
<a href="<?php the_permalink(); ?>" id="post-<?php the_ID(); ?>"><?php post_thumb(); ?><?php the_time('Y.m.d'); ?><?php the_title(); ?></a>

listやらpやらにクラス指定でスタイルを入れてあげる感じで。

もっとスマートなやり方があるかもしれないですけども。

%d人のブロガーが「いいね」をつけました。