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

如何为分页的WordPress文章/页面短链接添加页码

实现带分页页码的WordPress短链接短代码

可以实现将当前子页面的页码添加到短链接中,只需要在现有代码基础上添加分页页码的获取与拼接逻辑即可。以下是修改后的完整代码:

function custom_get_shortlink($post_id, $page_number = 0) {
    if (!$post_id) {
        return false;
    }
    $shortlink = wp_get_shortlink($post_id);
    // 如果有有效页码,添加到短链接中
    if ($page_number > 1) {
        // 使用add_query_arg安全添加查询参数,兼容文章分页(page)和归档分页(paged)
        $shortlink = add_query_arg(array(
            'page' => $page_number,
            'paged' => $page_number
        ), $shortlink);
        // 注:如果你的网站只用到其中一种分页类型,可以只保留对应的参数,比如只留'page'
    }
    return $shortlink;
}

function display_custom_shortlink() {
    global $post;
    if (!$post) {
        return;
    }
    $post_id = $post->ID;
    // 获取当前分页页码:文章分页用page,归档分页用paged,取有效值
    $page_number = get_query_var('page') ?: get_query_var('paged');
    $shortlink = custom_get_shortlink($post_id, $page_number);
    
    if ($shortlink) {
        echo '<a href="' . esc_url($shortlink) . '">短链接</a>';
    }
}

function custom_shortlink_shortcode() {
    ob_start();
    display_custom_shortlink();
    return ob_get_clean();
}
add_shortcode('custom_shortlink', 'custom_shortlink_shortcode');

关键改动说明:

  • 获取分页页码:使用get_query_var('page')获取文章内部分页(通过<!--nextpage-->拆分的子页面)的页码,get_query_var('paged')获取归档/列表页的分页页码,两者取有效值。
  • 安全拼接参数:用WordPress内置函数add_query_arg来添加分页参数,避免手动拼接URL导致的安全问题和格式错误。
  • 参数兼容:同时添加page和paged参数确保两种分页场景都能正常跳转,你可以根据自己网站的实际分页类型只保留其中一个参数。
  • 边界判断:只有当页码大于1时才添加参数,避免给第一页的短链接添加多余参数。

使用说明

替换你原来的代码后,在文章或页面中使用[custom_shortlink]短代码,生成的短链接会自动带上当前子页面的页码,比如第一页短链接为https://example.com/?p=123,第二页则为https://example.com/?p=123&page=2&paged=2(根据实际分页类型生效)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:07:20