記事に挿入されているサムネイル画像を取得して、表示する関数。
201005/02 Category : WEB Tag : php, Wordpress
記事に挿入されている画像のサムネイルを取得して表示するコード。ついでに、画像がない記事の場合は指定した画像を表示する。なんかむりっくり感があるけど、とりあえずは動いてます。
<?php
/* $typeに、'thumbnail'|'medium'|'large'|'full'のどれか指定
下記は'thumbnail'を指定 */
function the_image($type='thumbnail',$num=0){
global $post;
$post_ID = $post->ID;
$files = get_children("post_parent={$post_ID}&post_type=attachment&post_mime_type=image");
if (!empty($files)){
$keys = array_keys($files);
$img_num=$keys[$num];
echo wp_get_attachment_image($img_num,$type);
}
elseif (empty($files)){
$noimage = "/img/noimage.png";
echo ("<img src=\"");
echo (bloginfo('template_url')."$noimage");
echo ("\" />");
}
}
?>
以上のコードをfunctions.phpに書き込んで、表示したい部分に
<?php the_image(); ?>
と記載。
参考サイト様:blog.knym.net Wordpressの投稿記事で使われているサムネイル画像などを取得する関数 the_image