The issue is that the get_posts
function is being called outside of the $TaxanomiesB
loop. Move it inside and make sure the current $TaxanomyB
is being used in the $args in get_posts
.
Add data to $TaxanomyAArray
and $TaxanomyBArray
at the end of each for-each loop, otherwise the first object in the array will just be empty.
You also need to re-initialze the $array
variables at the start of each parent loop, otherwise you’ll end up with repeats of each post/taxonomy multiple times per set (like 'a' => (1 => (foo, bar), 2 => (foo, bar, foo, bar)), 'b' => 1 => (foo, bar, foo, bar, foo, bar)
…etc).
$TaxanomiesA = get_terms("TaxanomyA", array('hide_empty' => false));
$TaxanomiesB = get_terms("TaxanomyB", array('hide_empty' => false));
$TaxanomyAArray = array();
foreach($TaxanomiesA as $TaxanomyA) {
$TaxanomyBArray = array();
foreach($TaxanomiesB as $TaxanomyB){
$args = array(//Arguments with $TaxonomyB);
$posts = get_posts( $args );
$postsArray = array();
foreach($posts as $post){
$postsArray[] = array (
'id' => $post->ID,
'name' => $post->title
);
}
$TaxanomyBArray[] = array (
'id' => $TaxanomyB->term_id,
'name' => $TaxanomyB->name,
'posts' => $postsArray
);
}
$TaxanomyAArray[] = array (
'id' => $TaxanomyA->term_id,
'name' => $TaxanomyA->name,
'TaxanomyB' => $TaxanomyBArray
);
}
$jsonOutput = array(
'JSON' => $TaxanomyAArray
);
echo json_encode($jsonOutput, JSON_UNESCAPED_SLASHES);