一般我们使用get_previous_post()和get_next_post()函数来获取WordPress文章的第一篇和第二篇,那么如何获取同一分类下的第一篇和第二篇,我们只需要在这两个函数中添加一个参数即可。
采用
get_previous_post(true)
Products
GG网络技术分享 2025-03-18 16:15 0
一般我们使用get_previous_post()和get_next_post()函数来获取WordPress文章的第一篇和第二篇,那么如何获取同一分类下的第一篇和第二篇,我们只需要在这两个函数中添加一个参数即可。 采用get_previous_post(true)
就是这样,你得到的是一个post对象。
这里得到的是类别1或类别2的文章,如果你想得到类别1和类别2的文章,那么你必须这样做。
// Create a new filtering function that will add our where clause to the queryfunction 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);
Demand feedback