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

跨自定义文章类型获取WordPress下一篇文章链接的方法

问题描述

当前在自定义文章类型页面时,使用以下代码获取下一篇文章链接:

function func_getnextlink() { 
    global $post;
    $html = '';
    
    $next_post = get_next_post();
    if($next_post) {
        $html .= '<a rel="next" class="next" href="' . get_permalink($next_post->ID) . '">NEXT</a>';
    }

    return $html;
} 

add_shortcode('getnextlink', 'func_getnextlink'); 

需要修改代码,实现不区分当前所属文章类型,在两种不同的自定义文章类型中跨类型获取下一篇文章链接。

解决方案

默认的get_next_post()会限制在当前文章类型内查询,因此我们改用WP_Query构建跨类型查询,直接筛选当前文章之后发布的目标类型文章。修改后的代码如下:

function func_getnextlink() { 
    global $post;
    $html = '';

    // 替换为你实际需要的两种自定义文章类型slug
    $allowed_post_types = array('custom_type_1', 'custom_type_2');

    // 构建跨类型查询参数
    $args = array(
        'post_type'      => $allowed_post_types,
        'post_status'    => 'publish',
        'posts_per_page' => 1,
        'orderby'        => 'date',
        'order'          => 'ASC',
        'date_query'     => array(
            array(
                'after'     => $post->post_date,
                'inclusive' => false,
            )
        ),
        'post__not_in'   => array($post->ID),
    );

    $next_post_query = new WP_Query($args);

    if ($next_post_query->have_posts()) {
        $next_post_query->the_post();
        $html .= '<a rel="next" class="next" href="' . get_permalink() . '">NEXT</a>';
        wp_reset_postdata(); // 重置查询上下文,避免影响后续内容
    }

    return $html;
} 

add_shortcode('getnextlink', 'func_getnextlink'); 

关键说明

  • 只需将$allowed_post_types数组中的custom_type_1和custom_type_2替换为你实际使用的自定义文章类型slug即可。
  • 查询通过date_query筛选当前文章发布时间之后的内容,按日期升序取第一篇,即为逻辑上的“下一篇”。
  • wp_reset_postdata()用于重置查询上下文,防止干扰主题其他部分的内容输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:00:05