You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress:自定义文章类型的上一篇/下一篇按钮如何按合理顺序排列?

解决方案:按Slug字母顺序实现自定义文章类型的前后跳转

问题原因

你原代码使用的get_previous_post()和get_next_post()默认有两个限制:

  • 按发布日期排序,而非slug字母顺序
  • 默认仅在当前帖子所属的分类/术语中查找,导致无法遍历全部自定义文章类型帖子

要实现忽略分类、按slug字母顺序的前后跳转,需要通过自定义WP_Query来实现。

完整代码实现

<?php
// 获取当前帖子对象
$current_post = get_post();
if (!$current_post) return;

// 替换为你的自定义文章类型名称(比如'product'、'portfolio')
$custom_post_type = 'your_custom_post_type';

// --------------------------
// 查询「上一篇」:slug字母顺序小于当前的最后一个帖子
// --------------------------
$prev_post_args = array(
    'post_type'      => $custom_post_type,
    'posts_per_page' => 1,
    'orderby'        => 'name', // 按post_name(slug)排序
    'order'          => 'DESC',
    'post_status'    => 'publish',
    'post__not_in'   => array($current_post->ID),
    'meta_query'     => array(
        array(
            'key'     => 'post_name',
            'value'   => $current_post->post_name,
            'compare' => '<',
            'type'    => 'CHAR'
        )
    )
);
$prev_post_query = new WP_Query($prev_post_args);

if ($prev_post_query->have_posts()) :
    $prev_post_query->the_post();
?>
    <a rel="prev" href="<?php the_permalink(); ?>">上一篇:<?php the_title(); ?></a>
<?php
    wp_reset_postdata(); // 重置查询,避免影响后续内容
endif;

// --------------------------
// 查询「下一篇」:slug字母顺序大于当前的第一个帖子
// --------------------------
$next_post_args = array(
    'post_type'      => $custom_post_type,
    'posts_per_page' => 1,
    'orderby'        => 'name',
    'order'          => 'ASC',
    'post_status'    => 'publish',
    'post__not_in'   => array($current_post->ID),
    'meta_query'     => array(
        array(
            'key'     => 'post_name',
            'value'   => $current_post->post_name,
            'compare' => '>',
            'type'    => 'CHAR'
        )
    )
);
$next_post_query = new WP_Query($next_post_args);

if ($next_post_query->have_posts()) :
    $next_post_query->the_post();
?>
    <a rel="next" href="<?php the_permalink(); ?>">下一篇:<?php the_title(); ?></a>
<?php
    wp_reset_postdata();
endif;
?>

关键说明

  • 替换自定义文章类型:将代码中的your_custom_post_type替换为你实际使用的自定义文章类型标识符。
  • 排序逻辑:orderby => 'name'指定按帖子的post_name(即slug)进行排序,确保是字母顺序。
  • 筛选逻辑:通过meta_query筛选出slug比当前帖子小(上一篇)或大(下一篇)的帖子,type => 'CHAR'保证字符串比较的准确性。
  • 查询重置:每次查询后调用wp_reset_postdata(),恢复全局帖子对象,避免干扰页面其他内容的渲染。

内容的提问来源于stack exchange,提问作者nicolas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:56:30