Created
August 25, 2014 05:52
-
-
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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