2

Hi i need to get the main taxonomy and sub taxonomy of a product in woocommerce . i know how to get taxonomy details .123 is product id .

$terms = get_the_terms(123, 'product_cat');

I know how to get taxonomy name also

 echo $terms[0]->name 

But my need is: Nokia 3110 is my mobile . So it is under electronics-> mobiles -->ordinary-->Single sim-->nokia 3110

id is 123 .

in product edit page on admin-panel nokia 3110 is under single sim [actually single sim is under electronics-> mobiles -->ordinary].But I Only checked the single sim check box, not checked electronics, mobiles, ordinary etc .

My need is from this id i need to get mainly in which taxonmy nokia 31110 is . The answer is It is in Electronics. And i need the second taxonomy also , that is i need to print it is under mobiles . How to get these details

Thank you .

i know how to get topmost taxonomy

function get_term_top_most_parent($term_id, $taxonomy){
    // start from the current term
    $parent  = get_term_by( 'id', $term_id, $taxonomy);
    // climb up the hierarchy until we reach a term with parent = '0'
    while ($parent->parent != '0'){
        $term_id = $parent->parent;

        $parent  = get_term_by( 'id', $term_id, $taxonomy);
    }
    return $parent;
}

but please help to find second top taxonomy .

2
  • 1
    You'll find useful informations here =)
    – Sladix
    Jan 14, 2016 at 10:32
  • But how can i find second parent . This function very help to find topmost parent .But how to find second most. Please look this .
    – tom
    Jan 14, 2016 at 12:58

1 Answer 1

2

Based on this answer, here is my function to get all your terms in an array :

function get_term_ancestors($post_id, $taxonomy){
    // Declare the array where we are going to store the terms
    $ancestors = array();
    // start from the current term
    $parent  = array_shift(get_the_terms($post_id,$taxonomy));
    // climb up the hierarchy until we reach a term with parent = '0'
    while ($parent->parent != '0'){
        $term_id = $parent->parent;

        $parent  = get_term_by( 'id', $term_id, $taxonomy);
        $ancestors[] = $parent;
    }
    return $ancestors;
}

Use as follow :

$ancestors = get_term_ancestors(123,'product_cat');

So with this function, your top level term will be :

$ancestors[count($ancestors)-1] // or array_pop($ancestors);

and your second top level parent will be

$ancestors[count($ancestors)-2] // or another array_pop($ancestors)

Please also note than you should check isset($ancestors[count($ancestors)-2]) before trying to access it

Warning : This will only work for products which are in one term. This function does not handle multiple terms

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy