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

相关推荐
VIP_CQCRE4 天前
用 Ace Data Cloud 自动发布 WordPress 文章:把 SEO 内容站变成长期增长资产
ai·自动化·seo·wordpress·acedatacloud
2601_965798479 天前
Renovate Theme Setup: Fast Contractor & Construction Site Architecture
theme·wordpress
2601_9657984710 天前
Salient Theme Setup Guide for Fast Creative WordPress Sites
数据库·web3·php·wordpress
2601_9657984713 天前
Boutique Business Consulting WordPress Architecture & SEO Setup
android·theme·wordpress
2601_9657984714 天前
Plastic Surgery Clinic Web Setup: Deploying Rejuvita WordPress
php·theme·wordpress
2601_9657984714 天前
Contractor Web Setup: Deploying Bathrooms & Kitchens Theme Fast
前端·web3·php·wordpress
e6zzseo21 天前
wordpress独立站seo怎么做才有效
seo·wordpress·独立站·内容优化·外链建设
Web极客码23 天前
如何让用户订阅WordPress评论?提升用户互动的有效策略
运维·服务器·wordpress
fobwebs23 天前
Wordpress Xstore 主题安装Elementor Pro 后找不到某些Elements 组件的解决方法
element·wordpress·form·xstore·pro elements·elementor pro
代龙涛24 天前
WordPress sidebar.php 侧边栏开发教程
开发语言·php·wordpress