小赖子的英国生活和资讯

为博文后面添加上一篇下一篇文章链接

阅读 桌面完整版

贝总要求, 在博文后面加入了 上一篇, 和下一篇博文的链接. 下一篇是比较新的 上一篇比较旧(时间比较早). 需要用到WP的两个函数, get_previous_postget_next_post. 需要通过 add_filter 对文章内容加上了过滤器 (在文章最后面/最前面) 添加上下博文链接.

直接上PHP代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
add_filter( 'the_content', 'show_next_prev_post_links' );
 
function show_next_prev_post_links($content) {
  $pages = '';
  if (is_single()) { // 只在文章页显示
    $prev_post = get_previous_post();
    if (!empty( $prev_post )) { // 上一篇博文 比较旧
        $pages .= "上一篇博文: <a href='/archives/".$prev_post->ID."'>$prev_post->post_title</a>";
    }  
    $next_post = get_next_post();
    if (!empty( $next_post )) { // 下一篇博文 比较新
        $pages .= " | 下一篇博文: <a href='/archives/".$next_post->ID."'>$next_post->post_title</a>";
    }
  } 
  return $content . $pages;
}
add_filter( 'the_content', 'show_next_prev_post_links' );

function show_next_prev_post_links($content) {
  $pages = '';
  if (is_single()) { // 只在文章页显示
    $prev_post = get_previous_post();
    if (!empty( $prev_post )) { // 上一篇博文 比较旧
        $pages .= "上一篇博文: <a href='/archives/".$prev_post->ID."'>$prev_post->post_title</a>";
    }  
    $next_post = get_next_post();
    if (!empty( $next_post )) { // 下一篇博文 比较新
        $pages .= " | 下一篇博文: <a href='/archives/".$next_post->ID."'>$next_post->post_title</a>";
    }
  } 
  return $content . $pages;
}

把上面代码 加入到 子主题 模块文件 functions.php 的最后即可. 清除缓存 WordPressCloudflare 的即可. 需要注意的是 get_previous_postget_next_post 只对文章有效, 对页面无效, 所以需要用 is_single 来判断是否是文章页.

需要注意的是 得根据情况 修改 上面代码中 上下博文的链接, 主要有三种方式:

HTML的人很多 我就不多说了. 这也是增加站点内链的一种方式, 兴许会有利于 搜索引擎优化呢. 贝总, 我对你是真爱啊.

英文: How to Add Next and Previous Posts Links in WordPress?

强烈推荐

微信公众号: 小赖子的英国生活和资讯 JustYYUK

阅读 桌面完整版
Exit mobile version