wordpress调用文章上一篇 下一篇的标题和链接

在WordPress中,你可以使用`get_adjacent_post()`函数来获取上一篇和下一篇文章的信息,并根据是否存在这些文章来显示相应的链接和提示。以下是一个示例代码,它会检查上一篇和下一篇文章是否存在,并相应地显示链接或提示信息:

复制代码
<?php
// Obtain the previous article
$prev_post = get_adjacent_post(true, '', true);
$prev_title = $prev_post ? $prev_post->post_title : '';
$prev_link = $prev_post ? get_permalink($prev_post->ID) : '';

// Get the next article
$next_post = get_adjacent_post(true, '', false);
$next_title = $next_post ? $next_post->post_title : '';
$next_link = $next_post ? get_permalink($next_post->ID) : '';

// wodepress.com Display the link and title of the previous article
if ($prev_post) {
    echo '<li><a href="' . esc_url($prev_link) . '" rel="prev">' . esc_html($prev_title) . '</a> 上一篇</li>';
} else {
    echo '<li>没有上一篇文章</li>';
}

// Display the link and title of the next article
if ($next_post) {
    echo '<li><a href="' . esc_url($next_link) . '" rel="next">' . esc_html($next_title) . '</a> 下一篇</li>';
} else {
    echo '<li>没有下一篇文章</li>';
}
?>

这段代码首先使用`get_adjacent_post()`函数获取上一篇和下一篇文章的对象。如果文章存在,它会获取文章的标题和链接,并输出一个包含链接和标题的列表项。如果文章不存在,它会输出一个提示信息。

请确保将这段代码放入你的WordPress主题模板文件中适当的位置,例如`single.php`(用于文章页面)。这样,每当访问一个文章页面时,它就会显示上一篇文章和下一篇文章的链接和标题,或者相应的提示信息。

记得在实际使用中,要确保对输出的内容进行适当的转义,以防止XSS攻击。在上面的代码中,`esc_url()`用于转义URL,`esc_html()`用于转义HTML内容。

原文

http://www.dulizhan.sh.cn/jianzhan/104.html

相关推荐
e6zzseo12 小时前
wordpress独立站seo怎么做才有效
seo·wordpress·独立站·内容优化·外链建设
Web极客码3 天前
如何让用户订阅WordPress评论?提升用户互动的有效策略
运维·服务器·wordpress
fobwebs3 天前
Wordpress Xstore 主题安装Elementor Pro 后找不到某些Elements 组件的解决方法
element·wordpress·form·xstore·pro elements·elementor pro
代龙涛4 天前
WordPress sidebar.php 侧边栏开发教程
开发语言·php·wordpress
代龙涛5 天前
WordPress header.php 与 footer.php 模板结构详解
开发语言·php·wordpress
Web极客码10 天前
如何在WordPress中添加动态内容
服务器·前端·wordpress
tommyjiatong12 天前
WordPress电商展示站服务器迁移指南
服务器·数据库·wordpress
IT大白鼠14 天前
WordPress组合漏洞wp2shell技术分析报告
wordpress·安全漏洞·wp2shell 漏洞
Markk16 天前
Wordpress及第三方支持工具docker容器化搭建
wordpress
Web极客码21 天前
WordPress SEO优化:提升网站排名的13个关键步骤
服务器·seo·wordpress