gpt4 book ai didi

wordpress - 通过 WordPress 中的自定义查询获取下一篇和上一篇文章链接

转载 作者:行者123 更新时间:2023-12-02 23:35:22 25 4
gpt4 key购买 nike

我正在尝试通过自定义查询获取文章帖子页面 (single.php) 上的下一篇和上一篇文章链接。我尝试过使用 previous_post_link()next_post_link()函数,但它们通过 ID 获取帖子。我的索引页上有以下循环查询:

$args = array(
'post_type' => 'auction_dates',
'paged' => $paged,
'posts_per_page' => 1,
'meta_key' => 'date_of_auction',
'orderby' => 'meta_value_num',
'order' => 'ASC');

正如您所知,帖子是按自定义字段“拍卖日期”而不是 ID 排序的。我希望使用该自定义字段而不是 ID 来获取单个文章页面上下一篇和上一篇文章的链接。有什么想法吗?

最佳答案

previous_post_link()next_post_link()正如文档所说,需要在循环内。但是单曲后呢?您打开一篇文章,即使您使用全局查询对象,它也不会具有与您的帖子列表相同的查询数据 - 给您带来奇怪和/或循环的结果。

对于仍在寻求答案的人,我创建了一个简单的函数 get_adjacent_posts() (不要将其与 get_adjacent_post() native WordPress 函数混淆),该函数始终会获取上一个和无论查询和函数的位置如何,下一篇文章都会发布。

您需要做的就是提供查询参数数组作为参数,它将返回一个包含上一个和下一个 WP po​​st 对象的数组。

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 个帖子上需要这个代码。

希望您觉得它有用!

关于wordpress - 通过 WordPress 中的自定义查询获取下一篇和上一篇文章链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40831815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com