获取某个分类(Category)下所有文章相关的标签(TAGS)
首先获取分类下的所有文章:
query_posts(array( 'post_type' => 'portfolio', 'showposts' => -1, 'tax_query' => array( array( 'taxonomy' => 'portfolio-class', 'terms' => $the_taxonomy, 'field' => 'term_id', ) ), 'orderby' => 'date', 'order' => 'DESC' ) );
去过所有posts对象:
$portfolio_vars = $wp_query->posts;
这样就可以获取到每个文章的 ID $portfolio_var->ID;
可以通过这个ID 获取到每个文章相关的标签:wp_get_post_terms($portfolio_var->ID, $taxonomy);
然后就可以循环取出各个标题的属性,存储到新的$relate_terms数组里
$portfolio_vars = $wp_query->posts; foreach($portfolio_vars as $portfolio_var){ //$portfolio_ids[] = $portfolio_var->ID; $term_list = wp_get_post_terms($portfolio_var->ID, $taxonomy); foreach($term_list as $term){ $relate_terms[$term->term_id][id] = $term->term_id; $relate_terms[$term->term_id][slug] = $term->slug; $relate_terms[$term->term_id][name] = $term->name; } } //print_r($relate_terms);
$relate_terms[$term->term_id][id] = $term->term_id; 使用标题的ID作为key,可以自动替换掉重复的标题。
现在就可以循环输出标签了:
if($relate_terms){ echo '<div class="tags option-set portfolio-categories" id="filters" data-option-key="filter">'; $filter[] = '<a href="#filter" data-option-value="*" class="selected" title="All">All</a>'; foreach ($relate_terms as $relate_term) { $filter[] = '<a href="#filter" data-option-value=".' . $relate_term[slug] . '" title="' . $relate_term[name] . '">' . $relate_term[name] . '</a>'; } echo join(' | ', $filter); echo '</div>'; }
这段代码试用于在 while( have_posts() ) : the_post(); endwhile; 输出文章之前,先显示某个分类下所有的标签! like this