I'm building out a custom taxonomy archive page that needs to list terms in order by their associated post's post_date
. I wrote this, it's working, but I hate resorting to custom SQL:
global $wpdb;
$post_types = array( 'series' );
$taxonomy = array( 'taxonomy' );
$order = 'DESC';
$sql = "SELECT DISTINCT t.*
FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt
ON t.term_id = tt.term_id
JOIN $wpdb->term_relationships AS tr
ON tr.term_taxonomy_id = tt.term_taxonomy_id
JOIN $wpdb->posts AS p
ON p.ID = tr.object_id
WHERE tt.taxonomy IN ( '" . implode( "','", $taxonomy ) . "' )
AND p.post_type IN ( '" . implode( "','", $post_types ) . "' )
ORDER BY p.post_date {$order};";
$terms_ordered_by_post_date = $wpdb->get_results( $sql );
Curious if anyone has a better solution?
post_date
" - what if a term is applied to more than one post? Which post'spost_date
should matter?DISTINCT
means that the terms will be unique and ordered by the associated post_date. Edit original explanation was terrible, updated.