Hide posts having children terms when display posts by category in edit.php

I have a custom post type called "ttc_infobit" that belongs to a custom taxonomy named "ttc_catalogue". This taxonomy is a hierarchical.

When I filter posts in edit.php by this taxonomy, I want to show only posts having the currently selected term, and not its children.

Read More

For example if my url is:

/wp-admin/edit.php?s&post_status=all&post_type=ttc_infobit&action=-1&m=0&lang=el&admin_page_template&ttc_catalogue=77&paged=1&mode=list&action2=-1

WordPress will shows posts having ttc_catalogue with id 77 but also shows posts having ttc_catalogue with ids 101 and 102 that are children ot the 77.

How can I filter edit.php to show only items with id=77?

Related posts

Leave a Reply

1 comment

  1. By default when you run a query for a hierarchical taxonomy term, WordPress also returns post from its children. This happen on backend and on frontend as well.

    'tax_query' argument has an argument 'include_children' that was introduced for the scope, from Codex:

    include_children (boolean) Whether or not to include children for hierarchical taxonomies.
    Defaults to true.

    So you should run a tax query to set that param to false, however is not possible run a tax query from a url, but you can act on 'pre_get_posts' and set it.

    See inline comments for further informations:

    add_action('pre_get_posts', function( $query ) {
      if ( // being sure the query is the right one
        ! is_admin() || ! $query->is_main_query()
        || ! ( $term = $query->get('ttc_catalogue') )
      ) return;
      // being sure the page is the right one
      $s = get_current_screen();
      if ( $s->id !== 'edit-ttc_infobit' ) return; 
      // prepare tax query
      $tax_query = array(
        'taxonomy' => 'ttc_catalogue',
        'terms' => array( $term ),
        'field' => is_numeric( $term ) ? 'id' : 'slug',
        'include_children' => FALSE
      );
      // set tax query
      $query->set( 'tax_query', array( $tax_query ) );
      // unset 'plain' ttc_catalogue argument
      $query->set( 'ttc_catalogue', '' );
    });