문제

I'd like to show all the taxonomies related to the posts in a category page (archive).

I've the following code

<?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>';
    }
?>

but it returns duplicates for taxonomies. I tried array_unique but it doesn't work. Could you please help. Thanks

도움이 되었습니까?

해결책

Separate the loops, like this:

<?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>';
?>

If there are many terms, the approach above can result in PHP memory error. Here is another approach:

<?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>';
?>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top