一般我们获取wordpress文章的上下篇都是用get_previous_post()与get_next_post()函数来获取,那么如何获取同分类下的上下篇文章呢,只需要给这俩函数加一个参数即可。
使用
get_previous_post(true) get_next_post(true)
即可,获取到的就是一个post对象。
这里获取到的是分类1 or 2的文章,如果你想获取分类1 and 2的文章,那么得这样。
// Create a new filtering function that will add our where clause to the query function date_filter_where( $where = '' ) { global $post; $where .= " AND post_date >= '".$post->post_date."'"; return $where; } //then create your own get previous post function which will take an array of categories eg: // $cats = array('1','2'); function my_get_previous_post($cats){ global $post; $temp = $post; $args = array( 'posts_per_page' => 1, 'post_type' => 'post', 'post_status' => 'publish', 'category__and' => $cats ); add_filter( 'posts_where','date_filter_where' ); $q = new WP_Query($args); remove_filter( 'posts_where','date_filter_where' ); while ($q->have_posts()){ $q->the_post; echo '<a href="'.get_permalink($post->ID).'">'.get_the_title($post->ID).'</a>'; } $post = $temp; wp_reset_query(); }
使用$cats = array('1','2'); my_get_previous_post($cats);
0 个评论