
如何利用WordPress代码在文章页面获取当前文章的上一篇/下一篇文章的标题和链接,下面web建站小编给大家简单介绍一下3中不同的方法!
方法一:使用previous_post_link()函数和next_post_link()函数
<?php
// 上一篇文章
previous_post_link('%link', '上一篇: %title');
// 下一篇文章
next_post_link('%link', '下一篇: %title');
?>
方法二:使用get_previous_post()和get_next_post()函数
<?php
$prev_post = get_previous_post();
$next_post = get_next_post();
if (!empty($prev_post)) {
echo '<a href="' . get_permalink($prev_post->ID) . '">上一篇: ' . get_the_title($prev_post->ID) . '</a>';
}
if (!empty($next_post)) {
echo '<a href="' . get_permalink($next_post->ID) . '">下一篇: ' . get_the_title($next_post->ID) . '</a>';
}
?>
方法三:自定义函数代码
1、在functions.php模板中新增以下代码:
function theme_adjacent_post_link($is_prev = true) {
global $post;
// 定义查询参数:严格按发布日期排序,限制在当前分类
$args = [
'post_type' => $post->post_type,
'posts_per_page' => 1,
'order' => $is_prev ? 'DESC' : 'ASC', // 上一篇按日期降序,下一篇按升序
'orderby' => 'post_date',
'exclude' => $post->ID, // 排除当前文章
'tax_query' => [] // 存储分类查询条件
];
// 获取当前文章的所有分类(支持自定义分类法)
$taxonomies = get_object_taxonomies($post, 'names');
foreach ($taxonomies as $taxonomy) {
$terms = wp_get_object_terms($post->ID, $taxonomy, ['fields' => 'ids']);
if (!empty($terms)) {
$args['tax_query'][] = [
'taxonomy' => $taxonomy,
'terms' => $terms,
'operator' => 'IN'
];
}
}
// 如果是层级分类(如category),添加父子关系限制
if (in_array('category', $taxonomies)) {
$args['category__in'] = wp_get_post_categories($post->ID);
}
// 执行查询
$query = new WP_Query($args);
if ($query->have_posts()) {
$query->the_post();
$title = apply_filters('the_title', get_the_title());
$url = esc_url(get_permalink());
$rel = $is_prev ? 'rel="prev"' : 'rel="next"';
wp_reset_postdata(); // 重置查询
return sprintf(
'<a href="%s" title="%s" %s>%s</a>',
$url,
esc_attr($title),
$rel,
esc_html($title)
);
}
return '<span>没有了</span>';
}
2、在需要的文章页面心中以下代码:
<div class="pre_page">上一篇:<?php echo theme_adjacent_post_link( true ); ?></div> <div class="next_page">下一篇:<?php echo theme_adjacent_post_link( false ); ?></div>
wordpress建站,如何实现多个网站调用的文章图片来自同一个文件夹
标签: wordpress代码, 获取上一篇文章, 获取下一篇文章
上面是“WordPress建站模版获取上一篇/下一篇文章的标题和链接的几种方法”的全面内容,想了解更多关于 wordpress 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_24643.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

一款AI换脸神器,一键生成创意照片和视频——Faceswapper
MongoDB如何利用正则表达式进行模糊查询?
CodeRabbit:一款基于人工智能的AI代码审查与总结工具
Epic Games游戏网页版入口,附2025年Epic Games热门游戏排行榜
网站建设时要避开哪些常见的错误?