WordPressの機能、投稿サムネイル画像(アイキャッチ画像)の使い方をご紹介。
使い方
まず、投稿編集画面に投稿サムネイル画像(アイキャッチ画像)を表示するために以下のコードをfunctions.phpに追加します。
/** 投稿サムネイル画像(アイキャッチ画像)を表示 */ if ( function_exists( 'add_theme_support' ) ) add_theme_support( 'post-thumbnails' );
これで編集画面で投稿サムネイル画像(アイキャッチ画像)のインターフェイスが有効になります。
次に、投稿一覧にもサムネイル画像を表示するために以下のコードをfunctions.phpに追加します。
/**投稿一覧にサムネイルを表示 */
if ( !function_exists('fb_AddThumbColumn') && function_exists('add_theme_support') ) {
// for post and page
add_theme_support('post-thumbnails', array( 'post', 'page' ) );
function fb_AddThumbColumn($cols) {
$cols['thumbnail'] = __('Thumbnail');
return $cols;
}
function fb_AddThumbValue($column_name, $post_id) {
$width = (int) 35;
$height = (int) 35;
if ( 'thumbnail' == $column_name ) {
// thumbnail of WP 2.9
$thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
// image from gallery
$attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
if ($thumbnail_id)
$thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
elseif ($attachments) {
foreach ( $attachments as $attachment_id => $attachment ) {
$thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
}
}
if ( isset($thumb) && $thumb ) {
echo $thumb;
} else {
echo __('None');
}
}
}
// for posts
add_filter( 'manage_posts_columns', 'fb_AddThumbColumn' );
add_action( 'manage_posts_custom_column', 'fb_AddThumbValue', 10, 2 );
// for pages
add_filter( 'manage_pages_columns', 'fb_AddThumbColumn' );
add_action( 'manage_pages_custom_column', 'fb_AddThumbValue', 10, 2 );
}
これで投稿一覧にもサムネイル画像が表示されるようになります。これで、どの画像をアイキャッチ画像として設定しているのかが一目瞭然になります。
設定したサムネイル画像(アイキャッチ画像)をテンプレート内で利用する
サムネイル画像(アイキャッチ画像)を表示する
ループ内で設定したサムネイル画像(アイキャッチ画像)を呼び出したいときは以下のコードで出力・表示します。
<?php the_post_thumbnail(); ?>
サムネイル画像(アイキャッチ画像)の有無で処理を分岐させる
以下の関数はサムネイル画像(アイキャッチ画像)が設定してある時とない時とで異なる結果を出力したいときに使います。
<?php
if ( has_post_thumbnail() ) {
// サムネイル画像(アイキャッチ画像)が設定されているときの処理
} else {
// サムネイル画像(アイキャッチ画像)が設定されていないときの処理
}
?>
この機能を使えばエントリー毎にサムネイルを表示したりすることが出来るようになります。
注意事項
以上の機能はWordPress 2.9から実装された機能です。

WordPressの投稿サムネイル画像(アイキャッチ画像)の使い方。 http://bit.ly/cqSePt
[...] WordPressの投稿サムネイル画像(アイキャッチ画像)の使い方-Blog Play Under World ここを参考にいじった。 [...]
『Wordpressの投稿サムネイル画像(アイキャッチ画像)の使い方 « Blog × Play Under World』 http://htn.to/mWeJGC
『Wordpressの投稿サムネイル画像(アイキャッチ画像)の使い方 « Blog × Play Under World』
RT @chi_bit_2011『Wordpressの投稿サムネイル画像(アイキャッチ画像)の使い方 « Blog × Play Under World』 http://htn.to/mWeJGC