0

我想在类别页面(存档)中显示与帖子相关的所有分类法。

我有以下代码

<?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 但它不起作用。能否请你帮忙。谢谢

4

1 回答 1

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>';
?>
于 2013-10-31T15:10:16.567 回答