How to get related taxonomies based on a category with mysql query?
I have a lot of custom taxonomies for my WordPress site. What I want to do is to Get Related Custom Taxonomies based on a Category.
Sample Structure: (Material, OS and Features are Custom Taxonomies.)
Post | Category | (CT)Material | (CT)OS | (CT)Features |
---|---|---|---|---|
P1 | A | iOS | OLED | |
P2 | B | Metal | GPS | |
P3 | C | Glass | Anroid | GPS |
So what I want:
- For Category A: its related taxonomies is OS and Features.
- For Category B: its related taxonomies is Material and Features.
- For Category C: its related taxonomies is OS, Material and Features.
I'm not very familiar with complex mysql query, Any help is greatly appreciated, Thanks.
Updated: 2022-04-01
I've been able to achieve it by modifying another SQL I got here earlier. My English is not very good, maybe these codes can help everyone to understand my needs. My concern at the moment is whether there is a more efficient and performant way to do this.
function get_related_taxonomies($base_term_id, $base_taxonomy, $post_type = 'post') {
global $wpdb;
$key = $base_taxonomy . ':' . $base_term_id;
if ($taxonomies = wp_cache_get($key, 'related_taxonomies')) {
return $taxonomies;
}
$results = $wpdb-get_results($wpdb-prepare(
SELECT related_tax.taxonomy
FROM {$wpdb-prefix}terms related
INNER JOIN {$wpdb-prefix}term_taxonomy related_tax ON (related_tax.term_id = related.term_id)
INNER JOIN {$wpdb-prefix}term_relationships related_rel ON (related_tax.term_taxonomy_id = related_rel.term_taxonomy_id)
INNER JOIN {$wpdb-prefix}posts posts ON (related_rel.object_id = posts.ID)
INNER JOIN {$wpdb-prefix}term_relationships base_rel ON (posts.ID = base_rel.object_id)
INNER JOIN {$wpdb-prefix}term_taxonomy base_tax ON (base_rel.term_taxonomy_id = base_tax.term_taxonomy_id)
INNER JOIN {$wpdb-prefix}terms base ON (base.term_id = base_tax.term_id)
WHERE
base_tax.taxonomy = '%s'
AND posts.post_type = '%s'
AND posts.post_status = 'publish'
AND base.term_id = %d
GROUP BY related_tax.taxonomy,
$base_taxonomy,
$post_type,
$base_term_id
));
$taxonomies = array();
foreach ($results as $result) {
if ($result-taxonomy !== $base_taxonomy) {
$taxonomies[] = get_taxonomy($result-taxonomy);
}
}
wp_cache_set($key, $taxonomies, 'related_taxonomies');
return $taxonomies;
}
Topic advanced-taxonomy-queries multi-taxonomy-query mysql custom-taxonomy Wordpress
Category Web