TransWikia.com

Get Child Category only

WordPress Development Asked by JoaMika on February 2, 2021

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)?

One Answer

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.

Answered by kero on February 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP