Created
April 17, 2018 11:35
-
-
Save ashokmhrj/567e3dd215b9c00c3d9e876e5069e490 to your computer and use it in GitHub Desktop.
Array sort as per heierachical
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Array sort as per heierachical */ | |
function sort_terms_hierarchicaly(Array &$cats, Array &$into, $parentId = 0) { | |
foreach ($cats as $i => $cat) { | |
if ( $cat->parent == $parentId ) { | |
$into[$cat->term_id] = $cat; | |
unset($cats[$i]); | |
} | |
} | |
foreach ($into as $topCat) { | |
$topCat->children = array(); | |
sort_terms_hierarchicaly($cats, $topCat->children, $topCat->term_id); | |
} | |
} | |
function array_hierarchical( Array &$mainArray, Array &$into ) { | |
if( count($mainArray) <= 0 ) { | |
return $into; | |
} | |
foreach( $mainArray as $main ): | |
$term = new stdClass; | |
$term->term_id = $main->term_id; | |
$term->name = $main->name; | |
$term->slug = $main->slug; | |
$term->term_group = $main->term_group; | |
$term->term_taxonomy_id = $main->term_taxonomy_id; | |
$term->taxonomy = $main->taxonomy; | |
$term->description = $main->description; | |
$term->parent = $main->parent; | |
$term->count = $main->count; | |
$term->filter = $main->filter; | |
$into[] = $term; | |
if( count( $main->children ) ) { | |
array_hierarchical( $main->children, $into ); | |
} | |
endforeach; | |
} | |
$cats = wp_get_post_terms( get_the_ID(), 'product_cat', array( 'orderby' => 'parent' ) ); | |
$categoryHierarchy = array(); | |
sort_terms_hierarchicaly( $cats, $categoryHierarchy ); | |
$cats = array(); | |
array_hierarchical( $categoryHierarchy, $cats ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment