WordPressで現在のページからn番目の記事をn件取得する方法
WordPress
posted: 2023/11/10
update: 2024/02/29
ググってもあまり汎用的な実装が出てこなかったのでメモ
現在の投稿ページに他おすすめ記事などを現在のページから次のn件出したいときにoffsetを使う方法が出てきたのですが、動的にどのページにも現在のページからn番目+1の記事をn件表示なおかつn件-n番目+1がn件を下回る場合は一番最初の記事を取得などの処理を入れたい場合が面倒だったので、投稿ナンバリングから計算して表示する方法で実装しました。
例えば、1番目の記事にそこから次の3件を(2、3、4)、2番目の記事には次の3件(3、4、5)..と表示したい場合、記事の総数が9記事だった場合、7番目の記事になると次の記事が2件しかなくて足りない分は最初の記事に戻って(8、9、1)と表示したい場合に下記のロジックで実装しました。
やりたいこと:n番目の記事にいる場合、n+1、n+2、n+3の3件を表示なおかつ、
記事のトータル数-nが3件を下回る場合はn+1、n+2、nに戻る
まずは投稿数を取得する関数と、最終的にはpost__inで表示しないといけないので、投稿数を投稿IDへ変換する関数をfunction.phpに追加します。post_typeは任意のカスタム投稿名を入れてください。
// 投稿番号を取得する関数
function get_post_number() {
global $post;
$current_post_id = $post->ID;
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'ASC',
);
$query = new WP_Query($args);
$post_number = 1;
while ($query->have_posts()) {
$query->the_post();
if (get_the_ID() == $current_post_id) {
break;
}
$post_number++;
}
wp_reset_postdata();
return $post_number;
}
// 投稿番号からIDへの変換関数
function get_post_id_by_number($post_number, $post_type = 'post') {
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1,
'orderby' => 'ID',
'order' => 'ASC',
'fields' => 'ids',
);
その後、single-任意のカスタム投稿名.phpに、表示したい箇所へ下記の処理を入れます。
n番目の記事にいる場合、n+1、n+2、n+3の3件を表示なおかつ、記事のトータル数-nが3件を下回る場合はn+1、n+2、nに戻る、という処理を剰余演算で計算します。
<?php
$current_post_number = get_post_number(); // 現在の記事の番号を取得
$total_posts = wp_count_posts('people')->publish; // カスタム投稿タイプの総数を取得
// 次の3つの記事の番号を計算
$next_post_ids = array();
for ($i = 1; $i <= 3; $i++) {
$next_post_number = ($current_post_number + $i) % $total_posts; //剰余演算で計算
if ($next_post_number == 0) {
$next_post_number = $total_posts;
}
// 投稿番号から投稿IDを取得
$next_post_id = get_post_id_by_number($next_post_number);
if ($next_post_id) {
$next_post_ids[] = $next_post_id;
}
}
$args = array(
'post_type' => 'post', //任意のカスタム投稿タイプ
'post__in' => $next_post_ids,
'posts_per_page' => 3,
'order' => 'ASC',
'orderby' => 'post__in',
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) :
$query->the_post();
?>
//...WP_Queryで表示する処理を以下に書く
表示したい件数は3でなくても可能です。