get_all_meta_children: Source code

By the Web Warlock, Friday, 14/May/2010 13:08

<?php function get_all_meta_children( $term_id = NULL , $add_parent = true , $field = '_parent' , $depth = -1 , $cur_depth = 0 , $use_cache = true ){
	global $wpdb;
	$meta_table = $wpdb->prefix . 'termmeta' ;
	if( !$term_id ) extract( get_term_query_vars() );
	if( ( !$cur_depth ) && $add_parent ){
		$all_children = array( $term_id ) ;
	} else {
		$all_children = array() ;
	} ;
	if( $use_cache ){
		$children = get_term_meta_children_from_cache( $term_id );
	};
	if( ( !$use_cache ) || ( !is_array( $children ) ) ){
		$query = "SELECT DISTINCT tt.term_id , tt.taxonomy FROM (($wpdb->term_taxonomy AS tt)";
		$query .= " LEFT JOIN $meta_table AS tm ON tm.term_id=tt.term_id)" ;
		$query .= " WHERE (tt.parent=%d) OR ((tm.meta_key=%s) AND (tm.meta_value=%s));" ;
		$query = $wpdb->prepare( $query , (double)$term_id , (string)$field , (string)$term_id ) ;
		list( $children , $taxonomies ) = array( array() , array() );
		$results = $wpdb->get_results( $query );
		foreach( $results as $result ){
			$children[] = ( $child_id = (int)$result->term_id );
			if( !isset( $taxonomies[$child_id] ) ) $taxonomies[$child_id] = array();
			$taxonomies[$child_id][] = $result->taxonomy;
		};
		$children = array_unique( $children );
		wp_cache_set( $term_id , $children , 'termmeta_children' );
		//Next one is most surely not needed, uncomment it if needed
		//wp_cache_set( $term_id , $taxonomies , 'termmeta_children_taxonomies' );
	};
 
	$all_children = array_merge( $all_children , $children ) ;
	if( ( $depth < 0 ) || ( $cur_depth < ( $depth ) ) ){
		$num_children = count( $children ) ;
		for( $cur_child = 0 ; $cur_child < $num_children ; $cur_child++ ){
			$all_children = array_merge( $all_children ,
				get_all_meta_children( $children[$cur_child] , false ,
					$field , $depth , $cur_depth + 1 , $use_cache ) ) ;
		} ;
	} ;
	if( !$cur_depth ) $all_children = array_map( 'intval' , $all_children );
	return $all_children ;
} ; ?>

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment