Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moskalukigor/ffff1d17bb537a037d50d1d3f482bc2f to your computer and use it in GitHub Desktop.
Save moskalukigor/ffff1d17bb537a037d50d1d3f482bc2f to your computer and use it in GitHub Desktop.
Get Taxonomy Terms By Other Taxonomy Term
<?php
function getTaxTermsByOtherTaxTerm($taxonomy_1, $term_id, $taxonomy_2, $post_type = NULL) {
global $wpdb;
$post_type_q = !empty($post_type_q) ? "AND p.post_type = '$post_type'" : "";
$sql = "SELECT r.object_id FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN $wpdb->posts AS p ON (p.ID = r.object_id AND p.post_status = 'publish' $post_type_q)
WHERE tt.taxonomy = '$taxonomy_1' AND t.term_id = $term_id";
$res = $wpdb->get_col($sql);
if ($res && count($res)) {
$o_ids = implode(',', $res);
$sql = "SELECT t.*, tt.* FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id
WHERE tt.taxonomy = '$taxonomy_2' AND r.object_id IN ($o_ids) GROUP BY t.term_id";
$res = $wpdb->get_results($sql);
var_dump($res);
return $res;
}
}
getTaxTermsByOtherTaxTerm('pa_color', 28, 'pa_country');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment