• RSS

[WP]query_postsで、現在閲覧中の記事を除いた記事一覧を表示する方法

  • このエントリーをはてなブックマークに追加
  • follow us in feedly

WordPressで、例えば「現在閲覧中の記事と同じカテゴリに属する他の記事を見てほしい」なんて場合に便利な、記事一覧の中から現在閲覧中の記事を除外する方法のご紹介です。

現在閲覧中の記事を除いた記事一覧

現在閲覧中の投稿ID(記事)を除外するためには post__not_in を使います。
<?php 
$id = get_the_ID();
if (have_posts()) :
query_posts(array('post__not_in' => array($id),'posts_per_page' => -1));?>

<?php endwhile; endif; ?>


現在閲覧中の記事と同じカテゴリーに属する記事一覧(現在閲覧中の記事除く)

指定されたカテゴリ(現在閲覧している記事が属するカテゴリ)の中から、post__not_in を使って現在閲覧中の投稿IDを除外します。
<?php
$id = get_the_ID();
$cat = get_the_category();
$cat = $cat[0];
$cat_slug = $cat->slug;
?>
<?php if (have_posts()) :
query_posts(array('post__not_in' => array($id),'category_name' => $cat_slug,'posts_per_page' => -1));?>

<?php endwhile; endif; ?>



  • このエントリーをはてなブックマークに追加
  • follow us in feedly

コメント

コメントを残す