WordPress文章页面是否为其所属的某个term分类中的最后一篇文章的函数:
//用在文章页面
//$tax_name---该文章所属分类法
//$term_id---该文章所属term分类(该分类归属$tax_name分类法)
//$post_id---该文章ID
//注意排序(决定性因素),这里是按照时间排序
//函数返回的是布尔值,可以直接用于判断
if ( ! function_exists( 'zzw_last_post_in_term' ) ) :
function zzw_last_post_in_term($tax_name,$term_id,$post_id) {
// 验证当前是否为单篇文章页面且属于分类"tt2"
if (!is_single() || !has_term($term_id, $tax_name, $post_id) ) {
return false;
}
// 查询分类"tt2"下按发布时间降序排列的最新文章
$args = array(
'tax_query' => array(
array(
'taxonomy' => $tax_name, // 若为自定义分类法需替换名称
'field' => 'term_id',
'terms' => $term_id,
)
),
'orderby' => 'date',
'order' => 'DESC',//或者: ASC 升序、DESC 降序
'posts_per_page' => 1,
'post_status' => 'publish'
);
$query = new WP_Query($args);
$is_last = false;
// 比较当前文章与查询结果
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
if ( get_the_ID() === $post_id ) {
$is_last = true;
}
}
}
// 重置查询防止影响后续循环
wp_reset_postdata();
return $is_last;
}
endif;
千万注意排序方式!

