Skip to content

Instantly share code, notes, and snippets.

@gmazzap
Created August 25, 2014 05:52
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 gmazzap/b0428852379f86ca7244 to your computer and use it in GitHub Desktop.
Save gmazzap/b0428852379f86ca7244 to your computer and use it in GitHub Desktop.
A WordPress template tag that retrieve terms from specific taxonomies attached to the all the currently queried posts (in main query).
function queried_posts_terms( $taxonomies = 'category' ) {
global $wp_query, $wpdb;
if ( empty( $wp_query->posts ) ) return FALSE;
$ids = wp_list_pluck( $wp_query->posts, 'ID' );
$taxonomies = array_filter( (array) $taxonomies, function( $tax ) {
if ( is_string( $tax ) ) {
$tax = sanitize_title( $tax );
return taxonomy_exists( $tax ) ? esc_sql( $tax ) : NULL;
}
} );
if ( empty( $taxonomies ) ) return FALSE;
$sql = "SELECT t.name, t.slug, t.term_group, tt.*
FROM {$wpdb->terms} t
INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
INNER JOIN {$wpdb->term_relationships} tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tr.object_id IN (" . implode( ', ', $ids ) . ")
AND tt.taxonomy IN ('" . implode( "', '", $taxonomies ) . "')
GROUP BY t.term_id";
return $wpdb->get_results( $sql );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment