Order get_terms() by hierarchy

function ev_test_data() {
    $title = 'Mens Levi\'s Jeans';
    $titles = str_replace( array("'", '"', '-', '\\' ), '', explode( ' ', trim($title)) );
    $cats = array();
    foreach ( $titles as $kw ) {
        $terms = get_terms( array(
            'taxonomy' => 'product_cat',
            'orderby' => 'parent', // I guess this is where I am lost.
            'hide_empty' => false,
            'name__like' => $kw,
        ) );
        foreach ( $terms as $term ) {
            $cats[] = $term->term_id;
        }
    }

    $finals = array();
    foreach ( $cats as $cat ) {
        $catobj = get_term_by( 'id', $cat, 'product_cat' );
        $tree = '';
        $ancentors = array_reverse(get_ancestors( $cat, 'product_cat', 'taxonomy' ), true);
        $i=1;
        foreach ( $ancentors as $ancentor ) {
            $sterm = get_term_by( 'id', $ancentor, 'product_cat' );
            $tree .= $i == 1 ? '<b>' . $sterm->name . '</b>' : ' > ' . $sterm->name;
            $i++;
        }
        $tree .= ' > ' . $catobj->name;
        $finals[$cat] = $tree;
    }

    echo '<pre>' . print_r( $finals, true ) . '</pre>'; 
}  

Out for this function of code

Array
(
    [4638] => Fashion > Womens Clothing
    [4699] => Fashion > Womens Handbags & Bags
    [4709] => Fashion > Womens Shoes
    [4461] => Fashion > Mens Accessories
    [4493] => Fashion > Mens Clothing
    [4512] => Fashion > Mens Shoes
    [4603] => Fashion > Womens Accessories
    [4779] => Fashion > Vintage > Mens Vintage Clothing
    [4821] => Fashion > Vintage > Womens Vintage Clothing
    [4290] => Fashion > Kids Clothing, Shoes & Accs > Boys Clothing (Sizes 4 & Up) > Jeans
    [4319] => Fashion > Kids Clothing, Shoes & Accs > Girls Clothing (Sizes 4 & Up) > Jeans
    [4354] => Fashion > Kids Clothing, Shoes & Accs > Unisex Clothing > Jeans
    [4500] => Fashion > Mens Clothing > Jeans
    [4660] => Fashion > Womens Clothing > Jeans
    [4666] => Fashion > Womens Clothing > Maternity > Jeans
) 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>