要仅显示当前类别中的帖子,而不显示子类别中的帖子,请使用pre_get_posts
要设置的动作挂钩\'include_children\' => FALSE
在里面tax_query
参数
add_action( \'pre_get_posts\', \'se342950_no_child_term_posts\' );
function se342950_no_child_term_posts( $query )
{
if ( is_admin() || ! $query->is_main_query() || ! $query->is_category() )
return;
$tax_obj = $query->get_queried_object();
$q_tax = [
\'taxonomy\' => $tax_obj->taxonomy,
\'terms\' => $tax_obj->term_id,
\'include_children\' => FALSE,
];
$query->query_vars[\'tax_query\'][] = $q_tax;
}
您只能通过该功能从父类别获取帖子
get_posts()
, 其中也包括
include_children
应设置为
FALSE.
// in category.php "get_queried_object()" returns WP_Term object
$tax_obj = get_queried_object();
$posts_from_parent = [];
if ( $tax_obj->parent != 0 )
{
$args = [
\'post_type\' => \'post\',
\'tax_query\' => [
[
\'taxonomy\' => $tax_obj->taxonomy,
\'terms\' => $tax_obj->parent,
\'include_children\' => FALSE,
]
]
];
$posts_from_parent = get_posts( $args );
}
更新显示子类别帖子。
类别。php
?>
<div class="col-sm-12 brand-review-global">
<h3> Brands Review </h3> <!-- here I want to show post of B -->
<?php
global $post;
//
// get child category
$tax_obj = get_queried_object();
$children = get_terms([
\'taxonomy\' => $tax_obj->taxonomy,
\'parent\' => $tax_obj->term_id,
\'fields\' => \'ids\',
]);
if ( is_array($children) && count($children) )
{
$child_cat_id = array_shift( $children );
//
// get posts from child category
$args = [
\'post_type\' => \'post\',
\'tax_query\' => [
[
\'taxonomy\' => $tax_obj->taxonomy,
\'terms\' => $child_cat_id,
\'include_children\' => FALSE,
]
]
];
$posts_from_child = get_posts( $args );
//
// display
foreach( $posts_from_child as $post)
{
setup_postdata( $post );
?>
<div class="brand-review">
<a href="<?php the_permalink();?>">
<?php the_post_thumbnail(); ?>
</a>
<!-- other things: the_title(), the_excerpt(), ... -->
</div>
<?php
}
wp_reset_postdata();
}
else
{
echo \'No data to display\';
}
?>
</div>
<?php