Skip to content

Instantly share code, notes, and snippets.

@benmay
Created October 29, 2012 04:25
Show Gist options
  • Save benmay/3971505 to your computer and use it in GitHub Desktop.
Save benmay/3971505 to your computer and use it in GitHub Desktop.
On taxonomy page. Wanted to sort posts by their membership to a taxonomy. Loops through and re-orders as per the order of $terms array.
/*
* Used on taxonomy.php template by calling $posts = resort_posts($posts);
* =============================
* Expects the $posts variable to be passed to it, and will loop through,
* and move all the image gallery posts to the end of the loop.
*
* Order is by following taxonomies:
* - Media Releases
* - Fact Sheets
* - Images
* - Videos
* - Audio Files
* - Good News Stories
*/
function resort_posts( $posts=array() )
{
$new_posts = array();
$terms = array( 'media-releases', 'fact-sheets', 'image-gallery', 'video-gallery', 'audio-files' );
// Loop through each post. Then foreach post;
// start checking what format it is & update the array.
foreach( $posts as $key=>$post ){
foreach( $terms as $term_key => $term ){
if( has_term( $term, 'mc-format', $post ) ){
$new_array [ $term_key ][] = $post;
unset($posts[$key]);
continue;
}
}
}
// Sort the keys, correct order
ksort( $new_array );
// Loop through and make a single level array now.
foreach($new_array as $post_array)
foreach($post_array as $post)
$new_posts[] = $post;
// $posts will contain any posts with no format, add them on last.
$posts = array_merge( $new_posts, $posts );
return $posts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment