Duplicates of categories in While-loop for posts

120 Views Asked by At

I don't have want to find out a bug or anything, I'm just bad at coding.

What have have is this code, to find my categories in the fourth level, and print out the descriptions:

<?php while ( have_posts() ) : 
        the_post();
        $array = get_the_terms( get_the_ID(), 'product_category' );
        $fourth_level = array_filter($array, function ($t) {        
            if($t->parent != 0 
                && get_term($t->parent, 'product_category')->parent  != 0
                && get_term(get_term($t->parent, 'product_category')->parent, 'product_category')->parent != 0
                && get_term(get_term(get_term($t->parent, 'product_category')->parent, 'product_category')->parent, 'product_category')->parent == 0) return true;
            else return false;
        });

        foreach($fourth_level as $company)
        {
            if(isset($company))
            {
                // Print out company info \\
                echo "<a href='http://stilius.se/wilink/store/products/category/" . $company->slug . "/?cat=" . $_GET["cat"] . "'>" . $company->description . "</a>";
            }
        }

The problem with the code is this: Every time a category (company) has more than one post (product) the code prints out multiple category descriptions.

Would there be an easy way to just check if the category description is already printed out and then prevent the printing of said category, or check if a there are multiple posts in the same category and then only print it once?

Thanks in advance!

0

There are 0 best solutions below