WrdoPress 教程 ·

WordPress 同分类上下篇文章实现自定义链接

在我们WordPress网站中,很多主题都会有用到文章的上下篇功能

WordPress官方中, 也提供了相关函数方法直接调用,例如

<?php previous_post_link('上一篇: %link') ?>
<?php next_post_link('下一篇: %link') ?>

但是这样的获取很简约,没能实现自定义。

下面简单粗暴点,直接贴代码看吧

<div class="next-prev-post clearfix">
	<?php
		$categories = get_the_category();
		$categoryIDS = array();
		foreach ($categories as $category) {
			array_push($categoryIDS, $category->term_id);
		 }
		$categoryIDS = implode(",", $categoryIDS);
	?>
	<div class="post-direction">
	<?php
		$prev_post = get_previous_post($categoryIDS);
		if (!empty( $prev_post )){ ?>
			<a href="<?php echo get_permalink( $prev_post->ID ); ?>" class="post-prev">
				<span class="post-way"><i class="fa fa-angle-left"></i> 上一篇</span>
				<span class="title"><?php echo $prev_post->post_title; ?></span>
			</a>
		<?php } else { ?>
			<a href="#" class="post-prev">
				<span class="post-way"><i class="fa fa-angle-left"></i> 上一篇</span>
				<span class="title">已是最后文章</span>
			</a>
	<?php } ?>
	</div>
	<div class="post-direction">
	<?php
		$next_post = get_next_post($categoryIDS);
		if (!empty( $next_post )){ ?>
			<a href="<?php echo get_permalink( $next_post->ID ); ?>" class="post-next">
				<span class="post-way"><i class="fa fa-angle-left"></i> 下一篇</span>
				<span class="title"><?php echo $next_post->post_title; ?></span>
			</a>
		<?php } else { ?>
			<a href="#" class="post-next">
				<span class="post-way">下一篇 <i class="fa fa-angle-right"></i></span>
				<span class="title">已是最新文章</span>
			</a>
		<?php } ?>
	</div>
</div>
请不要直接copy代码使用,我这是结合自己的主题的样式进行部署的代码。仅供参考

最终结果

参考文章

参与评论