首页 论坛 WordPress 获取上一篇下一篇文章的标题和链接
帖子详情

如何获取到 WordPress 上一篇下一篇文章的链接,我马上想到了 previous_post_link() 和 next_post_link() 函数,这两个函数是输出 WordPress 上一篇下一篇文章的代码,通过查看其 API 文档,发现并没有直接获取链接的方式,整个函数是直接输出的。

https://www.wenjiangs.com/article/wordpress-previous-next-post-link.html

一般我们添加上一篇和下一篇文章时的代码是这样子的:

<?php previous_post_link('%link','%title',true) ?>
<?php next_post_link('%link','%title',true) ?>

该代码最终解析出来的代码大概如下:

<a href="……" rel="external nofollow" rel="external nofollow" > …… </a>
<a href="……" rel="external nofollow" rel="external nofollow" > …… </a>

这样子的结构是非常简单,如果我要增加 title、target 等属性值时,单靠上面两个函数是办不到的。

其实要解决这个问题很简单,不知道大家有没有接触到这两个函数:get_previous_post、get_next_post。通过这两个函数我们可以获取到上一篇和下一篇文章的相关信息。

大家可以到官网看看这两个函数的介绍。

<?php $prev_post = get_previous_post();$next_post = get_next_post();?>

上一篇文字:

<?php echo $prev_post->post_title; ?>

上一篇链接:

<?php echo get_permalink( $prev_post->ID ); ?>

下一篇文字:

<?php echo $next_post->post_title; ?>

下一篇链接:

<?php echo get_permalink( $next_post->ID ); ?>

好了,下面就来干货,说下解决问题的方法。只要将:

<?php previous_post_link('%link','<<') ?>
<?php next_post_link('%link','>>') ?>

替换成:

<?php
$prev_post = get_previous_post();
if (!empty( $prev_post )): ?>
<a title="<?php echo $prev_post->post_title; ?>"
href="<?php echo get_permalink( $prev_post->ID ); ?>"
rel="external nofollow" ><?php echo $prev_post->post_title; ?></a>
<?php endif; ?>
<?php
$next_post = get_next_post();
if (!empty( $next_post )): ?>
<a title="<?php echo $next_post->post_title; ?>"
href="<?php echo get_permalink( $next_post->ID ); ?>"
rel="external nofollow" ><?php echo $next_post->post_title; ?></a>
<?php endif; ?>

通过上面的替换,问题就完美解决了。除了可以添加 title 属性外,大家如果有需要也可以加上新窗口打开的属性:target:”_blank”。

版权:言论仅代表个人观点,不代表官方立场。转载请注明出处:https://www.52diyhome.com/forum/66023.html

发表评论
暂无评论
  • 0 +

    访问总数

  • 0 +

    会员总数

  • 0 +

    资源总数

  • 0 +

    今日发布

  • 0 +

    本周发布

  • 0 +

    运行天数

资源在于分享,创作来源想象