WordPress get_posts()とquery_posts() それぞれでの特定記事を除外した一覧取得

この記事は年前に書かれました。不適当な記述を含む場合がありますので、参考程度に留めてください。

どうもこんにちは。Toshikuraです。今回のTipsは【Wordpress get_posts()とquery_posts() それぞれでの特定記事を除外した一覧取得】です。記事一覧から特定記事を表示させない場合や詳細ページにて同一カテゴリから現在の記事を除外したい場合に使えますのでメモしておきます。

get_posts

get_postでは’exclude’を用いて指定した記事を除外します。さらに詳しく知りたい場合はテンプレートタグ/get postsをご参照ください。

記事ID「20」を除外した一覧

<?php $posts = get_posts(array('exclude' => 20,'posts_per_page' => 10));?>
<?php if($posts): foreach($posts as $post): setup_postdata($post); ?>

<?php endforeach; endif; ?>
現在の記事を除外した一覧

<?php
$id = get_the_ID();
?>
<?php $posts = get_posts(array('exclude' => $id,'posts_per_page' => 10));?>
<?php if($posts): foreach($posts as $post): setup_postdata($post); ?>

<?php endforeach; endif; ?>
現在の記事と同じカテゴリーの一覧

<?php
$cat = get_the_category();
$cat = $cat[0];
$cat_id = $cat->cat_ID;
?>
<?php $posts = get_posts(array('posts_per_page' => 10,'category' => $cat_id));?>
<?php if($posts): foreach($posts as $post): setup_postdata($post); ?>

<?php endforeach; endif; ?>
上記から現在の記事を除外した一覧

<?php
$id = get_the_ID();
$cat = get_the_category();
$cat = $cat[0];
$cat_id = $cat->cat_ID;
?>
<?php $posts = get_posts(array('exclude' => $id,'posts_per_page' => 10,'category' => $cat_id));?>
<?php if($posts): foreach($posts as $post): setup_postdata($post); ?>

<?php endforeach; endif; ?>

query_posts

get_postでは’exclude’を用いて指定した記事を除外します。さらに詳しく知りたい場合はテンプレートタグ/query postsをご参照ください。

記事ID「20」を除外した一覧

<?php if (have_posts()) : query_posts(array('post__not_in' => array(20),'posts_per_page' => 10));?>

<?php endwhile; endif; ?>
現在の記事を除外した一覧

<?php $id = get_the_ID(); ?>
<?php if (have_posts()) : query_posts(array('post__not_in' => array($id),'posts_per_page' => 10));?>

<?php endwhile; endif; ?>
現在の記事と同じカテゴリー(スラッグ)の一覧

<?php
$cat = get_the_category();
$cat = $cat[0];
$cat_slug = $cat->slug;
?>
<?php if (have_posts()) : query_posts(array('category_name' => $cat_slug,'posts_per_page' => 10));?>

<?php endwhile; endif; ?>
上記から現在の記事を除外した一覧

<?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' => 10));?>

<?php endwhile; endif; ?>

以上になります。