Sort post objects assigned to a taxonomy terms but not it’s children

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPrint this page

Per WordPress Codex when creating a custom query, and request objects which belong to a specific term, direct assigned objects will be included. Also all other objects which belong to child terms related to queried term will be returned too. This is the default behavior observed within WordPress dashboard, when filter for a specific category, all posts assigned to the term and it’s child will be show.

For example, we have a Blog category and a child Subcategory.

When filter for posts which are assigned to Blog, the dashboard also include posts assigned to it’s child Subcategory:

From above image, it can be seen that actually only 3 posts are direct objects of Blog category.

The explained practice works quite well in custom codes (themes and plugins), is the default way WordPress Query core works. The Advanced Post Types Order plugin, does just that and follow the standards.

What if we need to sort only object assigned to a taxonomy term but not it’s children?

The WordPress Codex mention a special parameter to make that happen, called include_children. This is set to TRUE as default, if being used within a custom query as FALSE, it returns only direct objects only.
The Advanced Post Types Order plugin include support for such parameter, so it let to chose through the sort settings if the children are actually required to be show, on not. Depending on the setting, the sort list include (or not) the children objects and it will apply on front side for queries which match that parameter, accordingly.

Here’s a sample code which use the include_children:

    $args = array(
                'post_type'                 => 'post',
                'tax_query'                 => array(
                                                array(
                                                    'taxonomy'          => 'category',
                                                    'field'             => 'term_id',
                                                    'terms'             => array(2),
                                                    'include_children'  =>  FALSE
                                                    )
                                                )
                );

    $query = new WP_Query($args);