Created
December 7, 2011 20:26
-
-
Save dalethedeveloper/1444480 to your computer and use it in GitHub Desktop.
Wordpress - Cross Taxonomy Tag List 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
<?php | |
/** | |
Echo a list of tags terms for posts that are also have a $where_tax of $where_slug | |
Queries added to transient cache for performance | |
Note: Using the slug for a Taxonomy in $where_slug for simpler query | |
Tested up to WP 3.3, drop it in your functions.php | |
Example: Get a tag list for Posts in the 'News' Category | |
tags_by_other_taxonomy('news'); | |
Example: Get a tag list for Bands (custom post type) in the 'Rock' Genre (custom taxonomy) | |
tags_by_other_taxonomy('rock','genre','band'); | |
*/ | |
function tags_by_other_taxonomy($where_slug,$where_tax = 'category',$post_type = 'post',$bust_cache = false) { | |
$cache_key = "{$where_slug}:{$where_tax}"; | |
$cache = get_transient('sc_cross_tax'); | |
if ( true !== $bust_cache and false !== $cache and isset($cache[$cache_key]) and !empty($cache[$cache_key]) ) { | |
echo '<!-- cache -->',$cache[$cache_key]; | |
} else { | |
global $wpdb; | |
$cat_id = $wpdb->get_var("SELECT tt.term_taxonomy_id FROM $wpdb->terms t INNER JOIN $wpdb->term_taxonomy tt ON t.term_id = tt.term_id WHERE t.slug = '{$where_slug}' AND tt.taxonomy = '{$where_tax}' LIMIT 1"); | |
if( !empty($cat_id) ) { | |
$cat_posts = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships tr inner join $wpdb->posts p ON p.ID = tr.object_id WHERE term_taxonomy_id = {$cat_id} AND p.post_status = 'publish' AND p.post_type = '{$post_type}'"); | |
if( count($cat_posts) ) | |
$tags = $wpdb->get_results("SELECT DISTINCT t.name,t.slug FROM $wpdb->term_taxonomy tt | |
INNER JOIN $wpdb->term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id | |
INNER JOIN $wpdb->terms t ON t.term_id = tt.term_id | |
WHERE tt.taxonomy = 'post_tag' and tr.object_id IN (".implode(',',$cat_posts) .')'); | |
$html = '<ul class="post-tags-'.$where_slug.'">'; | |
if( count($tags) ) { | |
foreach($tags as $tag) { | |
$html .= '<li><a href="/tag/'.$tag->slug.'/" title="Posts tagged with '.$tag->name.'">'.$tag->name.'</a></li>'; | |
} | |
} | |
$html .= '</ul>'; | |
if( !is_array($cache) ) | |
$cache = array(); | |
$cache[$cache_key] = $html; | |
set_transient('sc_cross_tax', $cache, 86400); | |
echo '<!-- no cache -->',$html; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment