Search code examples
wordpresscategoriesadvanced-custom-fieldstaxonomytaxonomy-terms

Get name of the taxonomy name from the term id


I have a custom user registration field call country, outlet, company (They're all taxonomy).

Eg. taxonomy=country&tag_ID=36&post_type=company

$country_tagid = the_field('country', 'user_'.$user_id->ID); //This output 36
$countrydata = get_terms('country',array('id'=>$country_tagid)); // 
echo $countrydata->name; //return nothing
$getcountrydata = get_term( $country_tagid );
print ($getcountrydata->name); //return nothing

All of them did not return the name. I expect it to return 'Thailand'. What is wrong?

EDIT: Strange, i manually entered outside the loop of my users.

<?php
    $catinfo = get_term_by( 'id', 36, 'country' );
    print $catinfo->slug; //thailand
?>

This works. I suspect something is wrong here

$country_tagid = the_field('country', 'user_'.$user_id->ID); //This output 36

This line prints 36. Now I'm trying to get_field. but it return me arr


Solution

  • I found out that this line is wrong. It did not store the value 36 in the variable. Instead it display it.

    $country_tagid = the_field('country', 'user_'.$user_id->ID); //This output 36
    

    I changed to get_field instead.

    $country_tagid = get_field('country', 'user_'.$user_id->ID); //This output 36
    

    I retrieve the id by

    $countryid= $country_tagid[0];
    

    Then retrieve the country name by:

    $catinfo = get_term_by( 'id', $countryid, 'country' );
    $countryname= $catinfo->name;
    

    So the full code:

    $country_tagid = get_field('country', 'user_'.$user_id->ID);
    $countryid= $country_tagid[0];
    $catinfo = get_term_by( 'id', $countryid, 'country' );
    $countryname= $catinfo->name;