WordPress函数:get_adjacent_post 获取相邻的文章

追格官方小助手/ 2023年02月13日/ WordPress/ 浏览 1522

WordPress站点中,在一篇文章的末尾,一般都有上一篇、下一篇的功能。实现这个功能,只需要使用 WordPress 函数 get_adjacent_post 即可。


函数原型:


get_adjacent_post( bool $in_same_term = false, int[]|string $excluded_terms = '', bool $previous = true, string $taxonomy = 'category' ): WP_Post|null|string


参数说明:


$in_same_term,是否要求与当前文章是同一类别。默认无要求。


$excluded_terms,要排除哪些类型。默认不排除。


$previous,true,前一篇;false,后一篇。默认:前一篇。


$taxonomy, 分类方式,默认为 post 的分类 category。


使用举例:


前一篇:


 <?php $prev_post = get_adjacent_post( true, '', true ); ?>
 <?php if ( is_a( $prev_post, 'WP_Post' ) ) { ?>
	<a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_title( $prev_post->ID ); ?></a>
 <?php } ?>


后一篇:


 <?php $next_post = get_adjacent_post( true, '', false ); ?>
 <?php if ( is_a( $next_post, 'WP_Post' ) ) {  ?>
	<a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo get_the_title( $next_post->ID ); ?></a>
 <?php } ?>


也可以直接使用 get_previous_post 和 get_next_post 函数。可以参考文章:《WordPress函数:get_previous_post 获取相邻的上一篇文章》 和 《WordPress函数:get_next_post 获取相邻的下一篇文章》

发表评论

暂无评论,抢个沙发...

客服 工单