記事で使われた画像を使って、記事へのリンクをテンプレート、またはサイドバー内に表示する方法について。
ver2.7でも動きます。
ver2.9の投稿サムネイル機能を使う関数はこちらにあります。
以前書いた画像のサムネイル表示(ループ内)の応用です。
この記事の関数は特定のカテゴリ下にある画像に絞っています。
全てのカテゴリーに対応したい場合はこちらの記事をご覧下さい。
テーマのfunctions.php内に次のソースをコピペ
function attachment_ancherlinks($my_id){ $args = "category=".$my_id; $posts = get_posts($args); print "<ul>"; for($i=0;$i<count($posts);$i++){ $attachments = get_children(array('post_parent' => $posts[$i]->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order')); $attachment = array_shift($attachments); $url = $posts[$i]->guid; $title= $posts[$i]->post_title; print "<li><a href="$url" title="$title">".wp_get_attachment_image($attachment->ID)."</a></li>"; } print "</ul>"; }
array_shift()をarray_pop()にすると逆になります。
get_posts()の引数を変更すると、表示件数などを変えられます。
上のソースはタイトルしか出してませんが、get_posts()使ってるので他の情報も表示させることが出来ます。
表示スタイル変更はprint()のくだりを適当に修正してください。
テンプレートファイルの表示したい場所に
attachment_ancherlinks($category_ID);
上記ソースを書くと、画像が表示されます。
サイドバーウィジェットはこんな感じで、
ウィジェットのコンテンツにテンプレートに書いたのと同じ関数を入れる。
register_sidebar_widget(__('PostImageLink','kubrick'), 'PostImageLink'); function PostImageLink($args){ extract($args); echo $before_widget; echo $before_title . $widget_name . $after_title; attachment_ancherlinks(5); echo $after_widget; }
データベースクエリとか使ったほうが早いのかなーと思いつつ。
ジェバンニが関数でやってくれました。
修正で分からないことがあればコメントください
実用的かもしれない修正版
- 表示件数の引数$numを追加して指定した任意の数だけ表示させる
- 画像が無い場合の例外処理
- カテゴリー名の表示
function attachment_ancherlinks($my_id, $num){ $args = "category=".$my_id."&numberposts=".$num; $posts = get_posts($args); print "<h3>".get_cat_name($my_id)."</h3>";//カテゴリー名 print "<ul>"; 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;//記事URL $title= $posts[$i]->post_title;//タイトル if(is_array($attachments)){ $attachment = array_shift($attachments); print "<li><a href="$url" title="$title">".wp_get_attachment_image($attachment->ID)."</a></li>"; }else{ //画像が無い場合 print "<li><a href="$url">$title</a></li>"; } } print "</ul>"; }
2.9以上の場合
どうもget_childrenの返り値が変わったっぽいので、
下記の通り、NoImage出力を判断しているif条件を変更してください
変更前:
if(is_array($attachments))
変更後:
if(count($attachments) >= 1)
参考記事