在 WordPress 中,你可以通过以下几种方式获取上一篇和下一篇文章的标题和链接,下面分别介绍在不同场景下的实现方法。

1. 在单篇文章模板(single.php)中获取


在单篇文章页面,通常会有导航显示上一篇和下一篇文章,方便用户浏览相关内容。以下是在 single.php 模板文件中实现该功能的代码示例:
收起
php
<?php
// 获取上一篇文章
$prev_post = get_previous_post();
if ($prev_post) {
    $prev_title = esc_attr($prev_post->post_title);
    $prev_link = get_permalink($prev_post->ID);
    echo '<a href="' . $prev_link . '">上一篇:' . $prev_title . '</a>';
} else {
    echo '没有上一篇文章了';
}

// 获取下一篇文章
$next_post = get_next_post();
if ($next_post) {
    $next_title = esc_attr($next_post->post_title);
    $next_link = get_permalink($next_post->ID);
    echo '<a href="' . $next_link . '">下一篇:' . $next_title . '</a>';
} else {
    echo '没有下一篇文章了';
}
?>

代码解释

 
  • get_previous_post():该函数用于获取当前文章的上一篇文章对象,如果没有上一篇文章则返回 false
  • get_next_post():用于获取当前文章的下一篇文章对象,若无下一篇文章则返回 false
  • esc_attr():对文章标题进行转义处理,防止 XSS 攻击。
  • get_permalink():根据文章 ID 获取文章的永久链接。

2. 自定义函数获取指定文章的上一篇和下一篇


如果你想在其他场景下获取指定文章的上一篇和下一篇文章的标题和链接,可以创建一个自定义函数,以下是示例代码:
收起
php
function get_prev_next_post_info($post_id) {
    // 获取上一篇文章
    $prev_post = get_adjacent_post(false, '', true, 'category');
    if ($prev_post) {
        $prev_title = esc_attr($prev_post->post_title);
        $prev_link = get_permalink($prev_post->ID);
        $prev_info = array(
            'title' => $prev_title,
            'link' => $prev_link
        );
    } else {
        $prev_info = false;
    }

    // 获取下一篇文章
    $next_post = get_adjacent_post(false, '', false, 'category');
    if ($next_post) {
        $next_title = esc_attr($next_post->post_title);
        $next_link = get_permalink($next_post->ID);
        $next_info = array(
            'title' => $next_title,
            'link' => $next_link
        );
    } else {
        $next_info = false;
    }

    return array(
        'prev' => $prev_info,
        'next' => $next_info
    );
}

// 使用示例
$post_id = get_the_ID(); // 当前文章 ID
$post_info = get_prev_next_post_info($post_id);

if ($post_info['prev']) {
    echo '<a href="' . $post_info['prev']['link'] . '">上一篇:' . $post_info['prev']['title'] . '</a>';
} else {
    echo '没有上一篇文章了';
}

if ($post_info['next']) {
    echo '<a href="' . $post_info['next']['link'] . '">下一篇:' . $post_info['next']['title'] . '</a>';
} else {
    echo '没有下一篇文章了';
}

代码解释

 
  • get_adjacent_post():该函数用于获取相邻的文章,第一个参数 false 表示不考虑文章的分类,第二个参数为空字符串表示不排除任何文章,第三个参数 true 表示获取上一篇文章,false 表示获取下一篇文章,第四个参数 'category' 表示按照分类来筛选相邻文章。

通过以上方法,你可以在 WordPress 中方便地获取上一篇和下一篇文章的标题和链接。