Order View of parent posts by count of child posts

If you have a parent-child relationship you may want to order a list of parent posts according to the number of child posts they have (e.g. show parent posts with more child posts first).

The following code gets the count of child posts for each parent and uses that to specify a custom order.

You would need to edit the slugs of the post types and relationship, and the ID(s) of the affected View(s).

/*
 * Order parent posts by child post count
 */
function tssupp_filter_query($view_args, $view_settings, $view_id) {
 
    // Edit slugs
    $parent_slug = 'project';
    $child_slug = 'task';
    $relationship_slug = 'project-task';
 
    if (in_array($view_id, array(855))) { // Edit View ID
 
        $parents = get_posts(array(
            'post_type' => $parent_slug,
            'nopaging' => true,
            'post_status' => 'publish',
            'tax_query' => $view_args['tax_query'],
        ));
 
        if (count($parents) > 0) {
 
            foreach ($parents as $parent) {
 
                $children = toolset_get_related_posts($parent->ID, $relationship_slug, array('query_by_role' => 'parent', 'role_to_return' => 'child', 'need_found_rows' => true));
                $parent->child_count = $children['found_rows'];
            }
 
            usort($parents, "custom_cmp");
 
            $parent_ids = wp_list_pluck($parents, 'ID');
 
            $view_args['post__in'] = $parent_ids;
            $view_args['post__not_in'] = null;
            $view_args['orderby'] = 'post__in';
        }
    }
    return $view_args;
}
add_filter('wpv_filter_query', 'tssupp_filter_query', 101, 3);
 
function custom_cmp($a, $b) {
    if ($a->child_count == $b->child_count) {
        return 0;
    }
    return ($a->child_count > $b->child_count) ? -1 : 1;
}

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments