カテゴリーベースの関連記事表示。
posts_per_pageに表示したい件数を数字で記述。下記例は4件表示。
テンプレートの表示したい部分に記述
<?php $categories = get_the_category($post->ID); $category_ID = array(); foreach($categories as $category): array_push( $category_ID, $category -> cat_ID); endforeach ; $args = array( 'post__not_in' => array($post -> ID), 'posts_per_page'=> 4, 'category__in' => $category_ID, 'orderby' => 'rand', ); $query = new WP_Query($args); ?> <div class="subcontent_title">関連する記事</div> <?php if( $query -> have_posts() ): ?> <ul> <?php while ($query -> have_posts()) : $query -> the_post(); ?> <li> <p> <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"> <?php if ( has_post_thumbnail() ): ?> <?php echo get_the_post_thumbnail($post->ID); ?> <?php else: ?> <img src="<?php echo get_template_directory_uri(); ?>/images/no_image.png" alt="NO IMAGE" title="NO IMAGE" /> <?php endif; ?> </a> </p> <p> <a href="<?php the_permalink(); ?>"> <?php the_title(); //記事のタイトル?> </a> </p> </li> <?php endwhile;?> </ul> <?php else:?> <p>記事はありませんでした</p> <?php endif; wp_reset_postdata(); ?>
HTML出力例
<div class="subcontent_title">関連する記事</div> <ul> <li> <p><img src="サムネイルのパス1.jpg"></p>http://ri-mode.com/memo/wp-admin/post-new.php#edit_timestamp <p>記事のタイトル1</p> </li> <li> <p><img src="サムネイルのパス2.jpg"></p> <p>記事のタイトル2</p> </li> <li> <p><img src="サムネイルのパス3.jpg"></p> <p>記事のタイトル3</p> </li> <li> <p><img src="サムネイルのパス3.jpg"></p> <p>記事のタイトル3</p> </li> </ul>