I am having an issue and not able to resolve it.
// get list of categories
$terms = $listing->get_field( 'region' );
foreach($terms as $t){
$parent_category = mg_get_term_parents( $t->term_id, 'region' );
}
When I dump parent_category I get an array (it prints only grandparent and parent) for child code is at the bottom.
array(2) {
[0]=>
object(WP_Term)#6446 (10) {
["term_id"]=>
int(213)
["name"]=>
string(8) "Americas"
["slug"]=>
string(8) "americas"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(213)
["taxonomy"]=>
string(6) "region"
}
[1]=>
object(WP_Term)#6448 (10) {
["term_id"]=>
int(157)
["name"]=>
string(13) "United States"
["slug"]=>
string(13) "united-states"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(157)
["taxonomy"]=>
string(6) "region"
}
}
or I get an array if grandparent is not presented.
object(WP_Term)#6454 (10) {
["term_id"]=>
int(214)
["name"]=>
string(4) "EMEA"
["slug"]=>
string(4) "emea"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(214)
["taxonomy"]=>
string(6) "region"
}
If I have only parent and child, I use the following and it gives me good results. But not sure what needs to be added here to cover all cases.
foreach( $terms as $t )
{
if ( $parent_category = mg_get_term_parents( $t->term_id, 'region' ) )
{
array_unshift( $terms, $parent_category );
}
}
$formatted_terms = array_filter( array_map( function( $term ) {
if ( ! $term = \MyListing\Src\Term::get( $term ) ) {
return false;
}
return [
'link' => $term->get_link(),
'name' => $term->get_name(),
'color' => $term->get_color(),
'text_color' => $term->get_text_color(),
'icon' => $term->get_icon( [ 'background' => false, 'color' => false] ),
];
}, $terms ) );
The problem occurs when I have grandparent, parent, and child. The solution above doesn't work.
If I use
$formatted_terms = array_filter( array_map( function( $term ) {
if ( ! $term = \MyListing\Src\Term::get( $term ) ) {
return false;
}
return [
'link' => $term->get_link(),
'name' => $term->get_name(),
'color' => $term->get_color(),
'text_color' => $term->get_text_color(),
'icon' => $term->get_icon( [ 'background' => false, 'color' => false] ),
];
}, $terms ) );
I print only 1 region from the array and the one that is missing which is a child. Array outputs only parent and grandparent. I need to add array output somehow to the code above tog et all needed.
Any idea how to accomplish this?