I was able to achieve this by, funnily enough, using with get_pages()
and WP_Query()
. I wanted a reusable function that would return a WP_Query array that I could loop through, so I came up with this:
function returnChildGeographies($geoID, $geoType, $grandChildren = false) {
$args = array(
'post_type' => 'geographies',
'posts_per_page' => -1,
'orderby' => 'post_title',
'order' => 'ASC',
'post_parent' => $geoID,
'tax_query' => array(
array(
'taxonomy' => 'geographytype',
'field' => 'slug',
'terms' => $geoType
)
)
);
if ($grandChildren) {
$getPagesArgs = array(
'sort_order' => 'ASC',
'sort_column' => 'post_title',
'hierarchical' => 0,
'child_of' => $geoID,
'post_type' => 'geographies'
);
$pagesArray = get_pages($getPagesArgs);
$grandChildArray = array();
foreach ($pagesArray as $grandchild) {
$grandChildArray[] = $grandchild->ID;
}
unset($args['post_parent']);
$args['post__in'] = $grandChildArray;
}
$childArray = new WP_Query($args);
return $childArray;
}
As an example usage: if I’m viewing the Americas area and I want to get all of the cities (which are which are grandchildren of the area), I call:
$regionQuery = returnChildGeographies($post->ID, 'city', true);
If I only want direct children:
$countryQuery = returnChildGeographies($post->ID, 'country', false);
Based on that last parameter, the function will unset post_parent
and set post__in
, which is an array of the post IDs I’m looking for.
The function could probably be neatened up quite a bit, but the method stands: combining get_pages()
and WP_Query()
seemed like the best way of getting grandchildren (or great-grandchildren, or great-great-grandchildren) and using a custom taxonomy query.