get_adjacent_post (获取相邻文章)
原文来自:http://www.liuweb.com/197.html
描述
获取上一篇或下一篇相邻的文章。
语法
get_adjacent_post( bool $in_same_term = false, array|string $excluded_terms = '', bool $previous = true, string $taxonomy = 'category' )
参数
$in_same_term:(bool) (Optional)( Default value: false) 文章是否在同一分类
$excluded_terms:(array|string) (Optional) (Default value: ”) 排除分类的ID
$previous:(boolean) (Optional) (Default value: true) 是否获取上一篇文章
$taxonomy:(string) (Optional)(Default value: ‘category’) 如果 $in_same_term 设置为 表示限定的分类
返回值
WP_Post:如果成功,返回文章对 象。
Null:如果 global $post 没有设置,返回空值Null。
String:如果不存在符合条件的文章 ,返回空字符串。
示例
获取同分类下的上一篇文章。
<?php $prev_post = get_adjacent_post( true, '', true, 'taxonomy_slug' ); ?>
<?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, 'taxonomy_slug' ); ?>
<?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 } ?>
关系
被用
wp-includes/link-template.php: get_adjacent_post_link()
wp-includes/link-template.php: get_previous_post()
wp-includes/link-template.php: get_next_post()
wp-includes/link-template.php: get_adjacent_post_rel_link()
源码
位置: wp-includes/link-template.php
function get_adjacent_post( $in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {
global $wpdb;
if ( ( ! $post = get_post() ) || ! taxonomy_exists( $taxonomy ) )
return null;
$current_post_date = $post->post_date;
$join = '';
$where = '';
$adjacent = $previous ? 'previous' : 'next';
if ( $in_same_term || ! empty( $excluded_terms ) ) {
if ( ! empty( $excluded_terms ) && ! is_array( $excluded_terms ) ) {
// back-compat, $excluded_terms used to be $excluded_terms with IDs separated by " and "
if ( false !== strpos( $excluded_terms, ' and ' ) ) {
_deprecated_argument( __FUNCTION__, '3.3.0', sprintf( __( 'Use commas instead of %s to separate excluded terms.' ), "'and'" ) );
$excluded_terms = explode( ' and ', $excluded_terms );
} else {
$excluded_terms = explode( ',', $excluded_terms );
}
$excluded_terms = array_map( 'intval', $excluded_terms );
}
if ( $in_same_term ) {