I am using this code to retrieve category:
$post_id = get_the_ID(); $countries = get_the_terms( $post_id, 'country' ); $fcountry = $countries[0]->slug;
However this sometimes retrieves the parent category of the countries (in our scenario the continent). How could I make this to always output the child category (i.e. the country)?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0