0

following code is returning name of all terms associated with my custom Post Type which are under `generetax taxonomy only

$terms = get_the_term_list($post->ID, 'generetax'); 
echo $terms;

Can you please let me know how to get the term_id instead of name? I tried this way

 echo $terms->term_id;

but it is not returning any thing

**

Update

**

Ok On rnnung this method

   $terms = get_the_terms($post->ID, 'generetax'); 
            foeach($terms as $term){
                print_r($term);
            }

WP_Term Object ( [term_id] => 3 [name] => Semi [slug] => semi [term_group] => 0 [term_taxonomy_id] => 3 [taxonomy] => generetax[description] => [parent] => 0 [count] => 1 [filter] => raw )

but still $terms->term_id; return nothing on

   $terms = get_the_terms($post->ID, 'generetax'); 
            foeach($terms as $term){
              echo  $terms->term_id;
            }
3
  • try foreach($terms as $term){print_r($term);} that should tell you what's going on. You can't echo an array, use print_r, var_dump, or var_export instead, then you'll know if it's an object or an array & what it contains..
    – admcfajn
    Feb 7, 2018 at 22:03
  • Thanks but I am getting this error Warning: Invalid argument supplied for foreach()
    – Mona Coder
    Feb 7, 2018 at 22:17
  • My bad. get_the_term_list returns string. get_the_terms will return an array of terms for a given taxo/post_id. get_terms will return all terms for a given-taxo.
    – admcfajn
    Feb 7, 2018 at 23:15

2 Answers 2

1

get_the_terms() will help you. Function return array with terms objects and you can foreach array and retrieve term id for each term attached to post.

0
0

If only getting ids of each term in array, no need to foreach each term item, just use php array_column native function :

$terms = get_the_terms($post_id, 'taxonomy');
$terms_ids = array_column($terms, 'term_id');
//output
[array_of_ids]

Kiss

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.