To display posts only from current category, without posts from sub-categories, use pre_get_posts
action hook to set 'include_children' => FALSE
in tax_query
parameter.
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;
}
Posts from only the parent category you can get with the function get_posts()
, in which also include_children
should be set to 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 );
}
Update
Display child category posts.
category.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="https://wordpress.stackexchange.com/questions/342950/<?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