I’ve created a custom taxonomy, for a custom post type, and created a custom page for it, the usual, etc.

Problem is I want to only show the custom posts that are part of the category, and not show the posts from the sub categories. So I wrote the following query for the loop:

<?php global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'post_type' => 'product', 'include_children' => 'false' ) );
query_posts( $args );
if(have_posts()) : while(have_posts()) : the_post(); ?>

Although 'include_children' => 'false' is included in the $args it still shows the products from the subcategories. I tried changing it for 'post_parent' => 0, and using them both at the same time, but to no avail.

Here is the code for my taxonomy:

function productcat_taxonomy() {

  $labels = array(
    'name' => _x( 'Product Categories', 'taxonomy general name' ),
    'singular_name' => _x( 'Product Category', 'taxonomy singular name' ),
    'search_items' =>  __( 'Search Product Categories' ),
    'all_items' => __( 'All Product Categories' ),
    'parent_item' => __( 'Parent Product Category' ),
    'parent_item_colon' => __( 'Parent Product Category:' ),
    'edit_item' => __( 'Edit Product Category' ), 
    'update_item' => __( 'Update Product Category' ),
    'add_new_item' => __( 'Add New Product Category' ),
    'new_item_name' => __( 'New Product Category Name' ),
    'menu_name' => __( 'Product Categories' ),
  );    

  register_taxonomy('product-category',array('product'), array(
    'hierarchical' => true,
    'labels' => $labels,
    'show_ui' => true,
    'show_admin_column' => true,
    'query_var' => true,
    'rewrite' => array( 'slug' => 'product-category' ),
  ));

}

add_action( 'init', 'productcat_taxonomy', 0 );

Where have I gone wrong?

3 Answers
3

There was a lot of hard coding going on in a number of these answers that I felt like may have disadvantages further down the road. Here is an approach that takes the existing tax_query, and swaps out the “include_children” argument.

As an aside, I did not have any luck setting “include_children” to false in this instance. I only found a zero to work.

function wpse239243_exclude_child_taxonomies( $query ) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if (is_tax('product-category')) {
            $tax_query = $query->tax_query->queries;
            $tax_query[0]['include_children'] = 0;
            $query->set( 'tax_query', $tax_query );
        }
    }
    return;
}
add_action( 'pre_get_posts', 'wpse239243_exclude_child_taxonomies', 1 );

Leave a Reply

Your email address will not be published. Required fields are marked *