
wp個別記事ページに同一タグの記事を表示する
Date 2016.02.24 Category blog
wordpressを使用した、ブログ等のカスタマイズで記事詳細ページで同じタグが付いた記事を呼びたい時のメモ。
wordpress見ている記事(シングルページ)に同一タグの記事を呼び出す
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 |
<?php $original_post = $post; $tags = wp_get_post_tags($post->ID); $tagIDs = array(); if ($tags) { $tagcount = count($tags); for ($i = 0; $i < $tagcount; $i++) { $tagIDs[$i] = $tags[$i]->term_id; } $args=array( 'tag__in' => $tagIDs, 'post__not_in' => array($post->ID), 'showposts'=>4, 'ignore_sticky_posts'=>1 ); $my_query = new WP_Query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <li> <h4> <a href="<?php the_permalink();?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> </h4> </li> <?php endwhile; wp_reset_query(); ?> <?php } else { ?> 関連する記事は見当たりません… <?php } } ?> |
13行目の ‘showposts’=>4, で表示させる関連記事数を設定します。
今回は4つの記事を表示させます。
複数タグがある場合も、全てのタグの関連記事を表示します。
サムネイル付きで表示したい場合は下記
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 |
<?php $original_post = $post; $tags = wp_get_post_tags($post->ID); $tagIDs = array(); if ($tags) { $tagcount = count($tags); for ($i = 0; $i < $tagcount; $i++) { $tagIDs[$i] = $tags[$i]->term_id; } $args=array( 'tag__in' => $tagIDs, 'post__not_in' => array($post->ID), 'showposts'=>4, 'caller_get_posts'=>1 ); $my_query = new WP_Query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <li> <span class="cat-thum"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>の詳細へ"><?php if ( has_post_thumbnail()) { the_post_thumbnail('thumbnail'); } else { echo '<img src="'.get_bloginfo('template_url').'/images/no-image.gif" alt="hoge" />'; }; ?></a> </span> <h4> <a href="<?php the_permalink();?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> </h4> </li> <?php endwhile; wp_reset_query(); ?> <?php } else { ?> 関連する記事は見当たりません… <?php } } ?> |