Get all custom taxonomies that are attached to posts that have another custom taxonomy


/ Published in: PHP
Save to your folder(s)

Get all custom taxonomies that are attached to posts that have another custom taxonomy. Like fetching all categories that are attached to products that have the brand taxonomy "Nike".


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. include('wp-load.php');
  4.  
  5. $nike = get_term_by('slug','nike','brand'); // This here just to illustrate
  6.  
  7. $terms = get_cross_referenced_terms(array(
  8. 'post_type' => 'product',
  9. 'related_taxonomy' => 'brand',
  10. 'term_id' => $nike->term_id,
  11. ));
  12. foreach($terms as $term) {
  13. echo "<p>{$term->name}</p>";
  14. }
  15.  
  16. function get_cross_referenced_terms($args) {
  17. global $wpdb;
  18. $args = wp_parse_args($args,array(
  19. 'post_type' => 'post',
  20. 'taxonomy' => 'category',
  21. 'related_taxonomy' => 'post_tag',
  22. 'term_id' => 0,
  23. ));
  24. extract($args);
  25. $sql = <<<SQL
  26. SELECT DISTINCT
  27.   {$wpdb->terms}.*,
  28.   COUNT(*) AS post_count
  29. FROM
  30.   {$wpdb->terms}
  31.   INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->terms}.term_id={$wpdb->term_taxonomy}.term_id
  32.   INNER JOIN {$wpdb->term_relationships} ON {$wpdb->term_taxonomy}.term_taxonomy_id={$wpdb->term_relationships}.term_taxonomy_id
  33.   INNER JOIN {$wpdb->posts} ON {$wpdb->term_relationships}.object_id={$wpdb->posts}.ID
  34.   INNER JOIN {$wpdb->term_relationships} related_relationship ON {$wpdb->posts}.ID=related_relationship.object_id
  35.   INNER JOIN {$wpdb->term_taxonomy} related_term_taxonomy ON related_relationship.term_taxonomy_id=related_term_taxonomy.term_taxonomy_id
  36.   INNER JOIN {$wpdb->terms} related_terms ON related_term_taxonomy.term_id=related_terms.term_id
  37. WHERE 1=1
  38.   AND (related_term_taxonomy.taxonomy<>{$wpdb->term_taxonomy}.taxonomy OR related_terms.term_id<>{$wpdb->terms}.term_id)
  39.   AND {$wpdb->posts}.post_type='%s'
  40.   AND {$wpdb->term_taxonomy}.taxonomy='%s'
  41.   AND related_term_taxonomy.taxonomy='%s'
  42.   AND related_terms.term_id=%d
  43. GROUP BY
  44.   {$wpdb->terms}.term_id
  45. SQL;
  46. $sql = $wpdb->prepare($sql,$post_type,$taxonomy,$related_taxonomy,$term_id);
  47. $terms = $wpdb->get_results($sql);
  48. return $terms;
  49. }

URL: http://wordpress.stackexchange.com/a/11005

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.