So if I understand correctly, the problem here is that get_the_terms(..)
returns both the parent and child category. As you said in the comment, there will only ever be 1 parent and 1 child in it, we can use that information to get the correct term.
Basically we need to filter the results, we know that one will have parent
not set while the other has it, so just get the latter one.
function joamika_get_country_from_post(int $postId): ?string {
$countries = get_the_terms($postId, 'country');
if (!is_array($countries)) {
return null;
}
array_filter($countries, function(\WP_Term $term): bool {
return $term->parent !== 0;
});
if (empty($countries)) {
return null;
}
return $countries[0]->slug;
}
$fcountry = joamika_get_country_from_post($post_id);
if ($fcountry === null) {
// something went wrong
}
// continue with your logic
If this is your first time seeing something like foo(int $postId): ?string {
, don’t worry. You can remove them or keep them. I prefer my PHP code to be as strictly typed as possible – you can read more about the topic here.
You still need to think about handling the case when no country is found.