Skip to content

Instantly share code, notes, and snippets.

@takien
Created December 15, 2012 08:21
Show Gist options
  • Save takien/4292111 to your computer and use it in GitHub Desktop.
Save takien/4292111 to your computer and use it in GitHub Desktop.
Order WordPress taxonomy (also category) by latest post.
<?php
/*
* taxonomy orderby latest post
* add new arg for taxonomy (include category),
* orderby=latest_post
* @author: takien.com
* the original version by http://jeffry.net (only for category)
*/
function filter_term_sort_by_latest_post_clauses( $pieces, $taxonomies, $args ) {
global $wpdb;
if ($args['orderby'] == 'latest_post' ) {
$pieces['fields'] .= ", MAX(p.post_date) AS last_date ";
$pieces['join'] .= " JOIN $wpdb->term_relationships AS tr JOIN $wpdb->posts AS p ON p.ID=tr.object_id AND tr.term_taxonomy_id=tt.term_taxonomy_id ";
$pieces['where'] .= " GROUP BY t.term_id ";
$pieces['orderby'] = " ORDER BY last_date ";
}
return $pieces;
}
add_filter('terms_clauses', 'filter_term_sort_by_latest_post_clauses', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment