previous_post_link() 和 next_post_link(),正如文档所说,需要在循环中。但是单曲后呢?您打开一篇文章,即使您使用全局查询对象,它也不会有与您的文章列表相同的查询数据 - 给您带来奇怪和/或循环的结果。
对于仍在寻求答案的任何人,我创建了一个简单的函数 get_adjacent_posts()(不要将它与 get_adjacent_post() 原生 wordpress 函数混淆),它总是会得到先前和下一篇文章,无论查询和函数的位置如何。
您需要做的就是提供查询 args 数组作为参数,它将返回一个包含上一个和下一个 WP post 对象的数组。
function get_adjacent_posts($args) {
global $post;
$all_posts = get_posts($args);
$len = count($all_posts);
$np = null;
$cp = $post;
$pp = null;
if ($len > 1) {
for ($i=0; $i < $len; $i++) {
if ($all_posts[$i]->ID === $cp->ID) {
if (array_key_exists($i-1, $all_posts)) {
$pp = $all_posts[$i-1];
} else {
$new_key = $len-1;
$pp = $all_posts[$new_key];
while ($pp->ID === $cp->ID) {
$new_key -= 1;
$pp = $all_posts[$new_key];
}
}
if (array_key_exists($i+1, $all_posts)) {
$np = $all_posts[$i+1];
} else {
$new_key = 0;
$np = $all_posts[$new_key];
while ($pp->ID === $cp->ID) {
$new_key += 1;
$np = $all_posts[$new_key];
}
}
break;
}
}
}
return array('next' => $np, 'prev' => $pp);
}
示例用法:
$args = array(
'post_type' => 'custom_post_type',
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'title'
);
$adjacent = get_adjacent_posts($args);
$next_title = $adjacent['next']->post_title;
$next_image = get_the_post_thumbnail_url($adjacent['next']->ID, 'square');
$next_url = get_permalink($adjacent['next']);
$prev_title = $adjacent['prev']->post_title;
$prev_image = get_the_post_thumbnail_url($adjacent['next']->ID, 'square');
$prev_url = get_permalink($adjacent['prev']);
警告:这个功能很耗费资源,所以如果你有很多帖子,请不要使用它。它从提供的查询中加载并迭代所有帖子以查找下一个和上一个帖子(如您在其代码中所见)。
有一个更好的方法可以做到这一点,即直接调用数据库,但无论如何我都懒得做,而且我在超过 100 个帖子上从来不需要这个代码。
希望你觉得它有用!