我想在类别页面(存档)中显示与帖子相关的所有分类法。
我有以下代码
<?php
$cat1 = $cat;
$args = array( 'posts_per_page' => -1, 'category' => $cat1 );?>
$myposts = get_posts( $args );
foreach ( $myposts as $post ) {
$product_terms = wp_get_object_terms($post->ID, 'Brands');
echo '<ul>';
foreach(array_unique($product_terms) as $term) {
echo '<li><a href="'.get_term_link($term->slug, 'Brands').'">'.$term->name.'</a></li>';
}
echo '</ul>';
}
?>
但它会返回分类法的重复项。我尝试过array_unique但它不起作用。能否请你帮忙。感谢
答案 0 :(得分:0)
将循环分开,如下所示:
<?php
$cat1 = $cat;
$args = array( 'posts_per_page' => -1, 'category' => $cat1 );?>
$myposts = get_posts( $args );
$myterms = array();
foreach ( $myposts as $mypost ) {
foreach ( wp_get_object_terms($mypost->ID, 'Brands') as $term ) {
$myterms[ $term->term_id ] = $term;
}
}
echo '<ul>';
foreach( $myterms as $term ) {
echo '<li><a href="'.get_term_link($term->slug, 'Brands').'">'.$term->name.'</a></li>';
}
echo '</ul>';
?>
如果有很多术语,上面的方法可能会导致PHP内存错误。这是另一种方法:
<?php
$cat1 = $cat;
$args = array( 'posts_per_page' => -1, 'category' => $cat1 );?>
$myposts = get_posts( $args );
$visited_term_ids = array();
echo '<ul>';
foreach ( $myposts as $mypost ) {
foreach ( wp_get_object_terms($mypost->ID, 'Brands') as $term ) {
if ( ! isset( $visited_term_ids[ $term->term_id ] ) ) {
echo '<li><a href="'.get_term_link($term->slug, 'Brands').'">'.$term->name.'</a></li>';
$visited_term_ids[ $term->term_id ] = TRUE;
}
}
}
echo '</ul>';
?>