patiboh
5/17/2016 - 4:11 PM

WordPress - Sort custom posts by taxonomy term groups

WordPress - Sort custom posts by taxonomy term groups

function sort_cars_by_model ( $cars = array() ) { /* array of car posts */
	$taxonomy = 'car_model';
	
	$tax_terms = get_terms( array(
			'taxonomy'   => $taxonomy,
			'orderby'    => 'name',
			'hide_empty' => false,
			'fields'     =>	'ids' 
	));
	return sort_custom_post_by_taxonomy_terms( $cars, $tax_terms, $taxonomy );
}
/**
 * Sort array of custom post objects by taxonomy terms
 * @param  array  $custom_posts [description]
 * @param  array  $tax_terms    [description]
 * @param  [type] $taxonomy     [description]
 * @return [type]               [description]
 */
function sort_custom_post_by_taxonomy_terms( $custom_posts = array(), $tax_terms = array(), $taxonomy ) {

  $sorted_output = array();
  
  /* for each taxonomy term add term id as an array key */
  foreach( $tax_terms as $tax_group ) {
    $sorted_output[ $tax_group ] = array();
  }
  
  /*
  
  OPTIMIZE : test this code
  
 //for each taxonomy term add term id as an array key
  array_map(function($term) {
    $sorted_output[ $term->term_id ] = array();
  }, $tax_terms);
  
  */
  
  /* for each post, if it contains a taxonomy term, add post id to taxonomy term array */
  foreach(  $custom_posts as $_post ) {
    $post_terms = get_the_terms( $_post, $taxonomy );
    if( $post_terms && ! is_wp_error( $post_terms ) ) {
      foreach( $post_terms as $term ) {
        $sorted_output[ $term->term_id ][] = $_post->ID;       
      }
    }   
  } // end term loop
  return $sorted_output;
}