[wordpress]関連記事表示の2つの方法

同じカテゴリに属するコンテンツを表示する

<?php
$categories = get_the_category();
foreach($categories as $category):
$related_posts = get_posts(array(
	'category__in' => array($category->cat_ID), 
	'exclude' => $post->ID, 
	'numberposts' => 3
	));
if($related_posts): ?>

<section id="related_posts">
	<h2>同じカテゴリーの関連記事</h2>
	
		<div class="related_posts row small-up-1 medium-up-3 large-up-3"  data-equalizer data-equalize-on="medium">
		
		<?php foreach($related_posts as $related_post):
			$thumbnail = get_post_thumbnail_id( $related_post->ID );
			$src_info = wp_get_attachment_image_src($thumbnail, 'medium');
			$src = $src_info[0];
			$width = $src_info[1];
			$height = $src_info[2];
			$title = $related_post->post_title;
			$date = get_the_date('Y.n.j');
		?>
		
			 <div class="column column-block">
				 <div class="card" data-equalizer-watch>
				<a href="<?php echo get_permalink($related_post->ID); ?>">
				<?php if ( has_post_thumbnail($related_post->ID) ) {
				echo '<img src="'.$src.'" alt="'.$title.'" width="'.$width.'" height="'.$height.'" />';
				} ?><div class="card-section"><span class="date"><?php echo $date ?></span><?php echo $title ?></div>
				</a>
				 </div>
			</div>
			<?php endforeach; ?>
		</div>
	<?php endif; endforeach; ?>
</section>

同じカスタムタクソノミーのコンテンツを表示する

<?php
global $post;
$terms = get_the_terms($post->ID, 'カスタムタクソノミー名'); ?>

<?php foreach((array)$terms as $term) { ?>

	<?php echo '<h3>' . $term->name . 'の関連記事</h3>'; ?>
	
	<?php $args = array(
        'numberposts' => 3, //3件表示
        'post_type' => 'post', //カスタム投稿タイプ名
        'taxonomy' => 'カスタムタクソノミー名', //カスタムタクソノミー名
        'term' => $term->slug, //ターム名
        'orderby' => 'rand', //ランダム表示
        'post__not_in' => array($post->ID) //表示中の記事を除外
    );
    ?>
    
    <?php $myPosts = get_posts($args); if($myPosts) : ?>
    <?php foreach($myPosts as $post) : setup_postdata($post); ?>
    
    	<?php the_title ?>
    	
    <?php endforeach; ?>
    <?php else : ?>
     <p>関連アイテムはまだありません。</p>
    <?php endif; wp_reset_postdata();
}
?>
共有
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
Posts published: 45
Copyrights © idew. All Rights Reserved.