前の記事で固定ページの子ページ一覧を表示できるショートコードをご紹介しました。
ただし、これは wp_list_pages でページ一覧をテキストリンクで表示するだけなのであまりに素っ気ないですよね。
というわけで、サムネイル画像をつけてみる方法をご紹介します。
※サムネイルは「アイキャッチ画像」で指定した画像を「サムネイル」サイズで出力します。
functions.php
function childpages($atts) { extract(shortcode_atts(array( 'parent' => null ), $atts)); if (empty($parent)) { // 指定なしなら自分の子 $top_post = get_post($post->ID); } else if ($parent=="parent") { // 自分の親ページを親とする parent="parent" $top_post = get_post($post->ID); $top_post = get_post($top_post->post_parent); } else { // スラッグ指定ページを親とする parent="(slug)" $top_post = get_page_by_path($parent); } $children = wp_list_pages("title_li=&child_of=".$top_post->ID."&echo=0"); return '<ul class="child-page">'.$children.'</ul>'; } add_shortcode("childpages", "childpages");
これが前回の記事で紹介したショートコードを実現するコード。
$children = wp_list_pages("title_li=&child_of=".$top_post->ID."&echo=0"); return '<ul class="child-page">'.$children.'</ul>';
HTML出力部分はこれ。ここを下記のように書き換えます。
$outhtml = '<ul>'; $childpages = get_pages( array( 'child_of' => $top_post->ID, 'sort_column' => 'menu_order' ) ); foreach( $childpages as $page ) { $outhtml .= '<li><a href="'.get_page_link( $page->ID ).'" title="'.$page->post_title.'">'; if ( has_post_thumbnail($page->ID) ) { $outhtml .= get_the_post_thumbnail($page->ID, 'thumbnail); } $outhtml .= '<h4>'.$page->post_title.'</h4>'; $outhtml .= '</a></li>'; } $outhtml .= '</ul>'; return $outhtml;
とりあえずプレーンなULリストで出力しているので適宜クラスやIDを付けて、CSSでスタイルをつけてください。
試しに、当サイトのWordPressマニュアルの目次をタイル状に並べてみたサンプルを表示してみます。
後記:
サンプルのようにするには、サムネイルがない場合の処理が面倒でした。
アイコンをきれいに表示したいから「NO IMAGE」をWebフォントのアイコンを表示したい
(ここを妥協すれば何も問題はなかったわけで・・)
↓
リキッド+レスポンシブで組んでるので、サムネイルのサイズを固定にできない
(普通は画像の幅をタイル幅の100%にして高さはナリにします)
↓
「NO IMAGE」のボックスの高さが決められない
(高さがずれるとタイルレイアウトが崩れる)
そこで、タイル内の画像ボックスを高さ固定にして、幅がはみ出す場合は左右均等にはみ出す部分をカットするようCSSで工夫してみました。
CSS例:サムネイル画像のサイズが300×135pxの場合
.thumb-image { height:135px; position:relative; background:#ccc; overflow: hidden; } .thumb-image img { position: absolute; top:0; left: 50%; margin-left:-150px; }