Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/791086f813d1d8920719 to your computer and use it in GitHub Desktop.
Save jchristopher/791086f813d1d8920719 to your computer and use it in GitHub Desktop.
Retrieve taxonomy terms in order of their post's post_date
<?php
global $wpdb;
$post_types = array( 'my_post_type' );
$taxonomy = array( 'my_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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment