因为@Ravs提到了中的第三个参数next_post_link()
/previous_post_link()
应为布尔值,指示是否将链接限制为同一类别中的帖子。默认情况下,这是false。如果设置为true,它将选择与当前帖子属于同一类别的下一篇(或上一篇)帖子。这包括所有父级(&A);子类别。
这些函数接受第三个参数:要排除的类别ID数组,但作为pointed out in the comments, 如果将“in same category”参数设置为true,则无法排除帖子所属的类别
因此,一种解决方案是将“同一类别”设置为false
, 并排除所有未与帖子关联的术语,或与帖子关联但其子级也与帖子关联的术语。(这相当混乱,您可以使用SQL filters 如果愿意的话)
以下返回与帖子关联的术语,以及具有与帖子关联的子术语的术语:
/**
* Returns a term IDs of terms that are associated with a post, and who have
* child terms also associated with the post.
*
* Please note, \'parent\' is a slight misnomer. If you have category structure:
* Cat A > Sub-Cat B > Sub-Sub-Cat C
* and a post belongs to A and B, but not C. \'B\' is not considered a parent term
* for this post.
*
* @link https://wordpress.stackexchange.com/questions/101633/restrict-post-navigation-to-current-sub-menu/102616#102616
* @param int $post_id. Optional, defaults to the \'current\' post.
* @return array An array of \'parent\' term IDs
*/
function wpse101633_get_parent_terms( $post_id = 0 ) {
$post_id = ( $post_id ? $post_id : get_the_ID() );
$terms = get_the_terms( $post_id, \'category\' );
$terms_with_children = array();
if( $terms ){
foreach( $terms as $t ) {
if( $t->parent && !in_array( $t->parent, $terms_with_children ) ){
$terms_with_children[] = $t->parent;
}
}
}
return $terms_with_children ;
}
用法示例:
Health warning: 我不做任何检查,所以如果帖子没有任何条款,你可能会出错。下面的逻辑是
$exclude_these
应封装在函数中,并移出模板以提高可读性。我变得懒惰了。
<?php if (is_single() ) {
$all_term_ids = get_terms( \'category\', array( \'fields\' => \'ids\' ) );
$post_terms = get_the_terms( get_the_ID(), \'category\' );
$post_terms = wp_list_pluck( $post_terms, \'term_id\' );
$parent_post_terms = wpse101633_get_parent_terms();
$child_terms = array_diff( $post_terms, $parent_post_terms );
//Exclude terms not associated with post, or that have a child who do.
$exclude_these = array_diff( $all_term_ids, $child_terms );
?>
<nav class="post-navigation">
<h1 class="visuallyhidden">Post Navigation</h1>
<ul>
<li class="prev"><?php previous_post_link( \'%link\', \'%title\', false, $exclude_these ); ?></li>
<li class="next"><?php next_post_link( \'%link\', \'%title\', false, $exclude_these ); ?></li>
</ul>
</nav>
<?php } ?>