Reputation: 392
I have created a custom taxonomy that acts like categories. Im using the following loop to show posts from this taxonomy:
$exec_query = new WP_Query( array (
'post_type' => 'cars',
'car_type' => 'large_cars',
'posts_per_page' => 100,
'order' => 'ASC',
'include_children' => false
) );
//* The Loop
if ( $exec_query->have_posts() ) { ?>
<?php
while ( $exec_query->have_posts() ): $exec_query->the_post();
get_template_part( 'parts/loop', 'single-produkt' );
endwhile; ?>
<?php
//* Restore original Post Data
wp_reset_postdata();
}
This displays all posts that are posted in the taxonomy "Large cars".
But this taxonomy have children categories like "SUV", "Vans" and posts from this childs are also shown. I do not want to show this, but include_children does not seem to work.
Any ideas?
Upvotes: 2
Views: 2672
Reputation: 392
Allright, found a solution by first getting the ID's of the child categories and then exclude them from the WP_Query-array:
$term_id = get_term_by( 'slug', $term, $taxonomy)->term_id;
$taxonomy_name = $taxonomy;
$termchildren = get_term_children( $term_id, $taxonomy_name );
$exclude = "";
foreach ( $termchildren as $child ) {
$term2 = get_term_by( 'id', $child, $taxonomy_name );
$exclude = $exclude . "" . $term2->term_id . ",";
}
$exclude = substr($exclude, 0, -1);
$args = array(
//Rest of you args go here
'tax_query' => array (
array(
'taxonomy' => $taxonomy, // My Custom Taxonomy
'terms' => explode(',', $exclude), // My Taxonomy Term that I wanted to exclude
'field' => 'id', // Whether I am passing term Slug or term ID
'operator' => 'NOT IN', // Selection operator - use IN to include, NOT IN to exclude
),
),
'post_type' => $type,
$taxonomy => $term,
'posts_per_page' => 100,
'order' => 'ASC',
);
Upvotes: 2
Reputation: 760
Try this,you have to use include_children as below to remove the children taxonomies.
$args = array(
//Rest of you args go here
'tax_query' => array(
array(
'include_children' => false
)
),
'post_type' => 'cars',
'car_type' => 'large_cars',
'posts_per_page' => 100,
'order' => 'ASC'
);
$query = new WP_Query( $args );
Upvotes: 1