WordPressで投稿画像のサムネイル表示

2011.12.28 12:19
 WordPressってテンプレートタグみたいなこと言っていますが、いったいどこがタグなんだかさっぱりわからない感じですね。
 トップページとかウィジェットの中で投稿したサムネイルを表示するPHPコード(テンプレートタグ)です。ほしかった機能というのはサムネイルをクリックすると画像が見られれるのではなくて、投稿した記事に飛ぶというものです。投稿した画像のない記事はスキップしています。あとは、CSSでいろいろ調整して整える感じです。

出力したHTMLはこんな感じになります。
<div id='photos-block'>
    <a href='http://www.laughlang.com/wp/?p=11' title='test'>
        <div class='resize_thumbnail'>
            <img width="200" height="150" src="http://www.laughlang.com/wp/wp-content/uploads/2011/11/new_year_card.png" class="attachment-thumbnail" alt="new_year_card" title="new_year_card" />
        </div>
    </a>
     ...
</div>
<div class="clear"></div>

タグだかコードだかはこんな感じです。
<div id='photos-block'>
<?php
$my_id = 0;
$num = 10;
$re = attachment_ancherlinks($my_id,$num);

function attachment_ancherlinks($my_id=0, $num){
    $args = "category=".$my_id."&numberposts=".$num;
    $posts = get_posts($args);

    for($i=0; $i <$num ;$i++){
        if($i>= count($posts) ) return;
            $attachments = get_children(array('post_parent' => $posts[$i]->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order'));
        $url = $posts[$i]->guid;
        $title= $posts[$i]->post_title;
        if(is_array($attachments)){
            $attachment = array_shift($attachments);
            if (wp_get_attachment_image($attachment->ID)) {
                print "<a href='".$url."' title='".$title."'><div class='resize_thumbnail'>".wp_get_attachment_image($attachment->ID)."</div></a>\n";
            }
        }
    }
}
?>
</div>
<div class="clear"></div>

ただ単にサムネイル表示したいだけなら、こっちです。
<?php while (have_posts()) : the_post(); ?>
<?php
$files = get_children("post_parent=$id&amp;post_type=attachment&amp;post_mime_type=image");
if (empty($files)){
#print "none";
}else{
$keys = array_keys($files);
        $lastkeys = array_pop($keys);
        $num=$lastkeys;
        $thumb=wp_get_attachment_image_src($num,'medium');
print '<img src="' . $thumb[0] . '" width="' . $thumb[1] . '" height="' . $thumb[2] . '" alt="' . $post->post_title . 'の画像">' . "\n";
}
?>
<?php endwhile; ?>







プロフィール



  • Name :: 山上オサム ♂(39)
  • Hobby :: 武術
  • Work :: Web Designer