先日ローカルにこのブログのコピーを作りましたが、関連記事のコードを入れてみました。
プラグインを入れすぎると重たくなるしメインテナンスも大変になるので、コードの勉強がてらやってみました。
コードそのものは難しいものでなく、タグが同じ記事を指定した数だけ表示するというものです。
基本的には以下のコードをsingle.phpのメイン記事が表示された後に挿入しました。
ただサムネイル画像で苦労しました。
サムネイル画像は、以下の2つの方法でやってみました。
1.単純に呼び出して表示する。
2.背景として表示する。
1.単純に呼び出して表示する。
has_post_thumbnailをIfで聞いてもしあれば、get_the_post_thumbnailでサムネイルを呼び出しています。サムネイルがなかったら、No-Imageの画像を呼び出してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<div class="relatedposts"> <h4>関連記事</h4> <?php $orig_post = $post; global $post; $tags = wp_get_post_tags($post->ID); if ($tags) { $tag_ids = array(); foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id; $args = array( 'tag__in' => $tag_ids, 'post__not_in' => array($post->ID), 'posts_per_page'=>6, // 表示する関連記事の数 'caller_get_posts'=>1, 'orderby' => 'rand', // 過去記事に内部リンクできる ); $my_query = new wp_query( $args ); ?> <div class="row"> <?php while( $my_query->have_posts() ) { $my_query->the_post(); ?> <div class="col-xs-6 inner"> <h5> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php if ( has_post_thumbnail() ): // サムネイルを持っているとき ?> <?php echo get_the_post_thumbnail($post->ID, 'thumb100'); //サムネイルを呼び出す?> <?php else: // サムネイルを持っていないとき ?> <img src="<?php echo get_template_directory_uri(); ?>/images/no-image.gif" alt="NO IMAGE" title="NO IMAGE"/> <?php endif; ?> <?php if (strlen($post->post_title) > 50) { echo mb_substr(the_title($before = '', $after = '', FALSE), 0, 50, 'UTF-8') . '...'; } else { the_title(); } ?> </a> </h5> <p> <?php $cat = get_the_category(); $cat = $cat[0]; echo '<a href="' . get_bloginfo('url') . '/category/' . $cat->category_nicename . '">'; echo $cat->cat_name; echo '</a>'; ?> </p> </div><!--col-xs-6 inner--> <?php } // while ?> </div><!--row--> <?php } // IF $post = $orig_post; wp_reset_query(); ?> </div><!--relatedposts--> |