Hi!请登陆

WordPress如何获取文章所属分类上下篇文章的URL链接地址?

2021-2-8 69 2/8

为了方便用户查看上下篇文章也为了所谓 SEO 优化,我们一般都喜欢在文章页后面添加上同分类的上下篇文章,不过一般情况下我们都无法修改上下篇文章的 URL 地址,只能默认输出,是什么样就是什么样。其实,我们完全可以换一种方式来输出自己想要的上下篇 URL 链接地址结构。

默认情况下同分类上下篇文章代码:

<?php 
$categories = get_the_category(); 
$categoryIDS = array(); 
foreach ($categories as $category) { 
array_push($categoryIDS, $category->term_id); 
} 
$categoryIDS = implode(",", $categoryIDS); ?> 
<?php if (get_previous_post($categoryIDS)) { previous_post_link('%link','%title',true,'');} ?> 
<?php if (get_next_post($categoryIDS)) { next_post_link('%link','%title',true,'');} ?>

上述代码中的第 8、9 行代码就是输出上下篇文章的 URL 链接地址和标题,但是其中的 URL 链接地址和标题我们都部分修改或自定义。为此,我们需要将第 8、9 行代码修改为以下代码:

<?php $prev_post=get_previous_post($categoryIDS);if (!empty( $prev_post )) { ?>
<a href="<?php%20echo%20get_permalink(%20$prev_post->ID%20);%20?>" rel="nofollow" ><?php echo $prev_post->post_title; ?></a>
<?php } ?> 
<?php $next_post = get_next_post($categoryIDS);if (!empty( $next_post )) { ?>
<a href="<?php%20echo%20get_permalink(%20$next_post->ID%20);%20?>" rel="nofollow" ><?php echo $next_post->post_title; ?></a>
<?php } ?>

这样一来,我们就可以自定义上下篇文章的 URL 链接地址和标题了。比如我想在上下篇链接地址后面添加上“/mip”和在 rel 中添加一些代码则修改为:

<?php $prev_post=get_previous_post($categoryIDS);if (!empty( $prev_post )) { ?>
<a href="<?php%20echo%20get_permalink(%20$prev_post->ID%20);%20?>/mip" rel="prev nofollow" ><?php echo $prev_post->post_title; ?></a>
<?php } ?> 
<?php $next_post = get_next_post($categoryIDS);if (!empty( $next_post )) { ?>
<a href="<?php%20echo%20get_permalink(%20$next_post->ID%20);%20?>/mip" rel="next nofollow" ><?php echo $next_post->post_title; ?></a>
<?php } ?>

即可。

相关推荐