0

i'm trying to list user's posted categories (main ones only) on the author.php

I have prepared this loop but it has duplicated content

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php 
$ar = get_the_category();
foreach($ar as $category) {

if ($category->category_parent == 0) {
echo '<p><a href="?author_name='.$curauth->user_login .'&cat='.$category->cat_ID.'" title="' . $category->name . '">' . $category->name . '</a></p>';
}
    }
?>

So after a little research they said array_unique() might work but it turns empty or NULL:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php 
$ar = get_the_category();
$cat = array_unique($ar);
foreach($cat as $category) {

if ($category->category_parent == 0) {
echo '<p><a href="?author_name='.$curauth->user_login .'&cat='.$category->cat_ID.'" title="' . $category->name . '">' . $category->name . '</a></p>';
}
    }
?>

Where i'm making the mistake??

How can i remove the duplicate category names in the foreach loop? To show each category only once?

updated: war_dump($r) outputs:

array(1) { [0]=> object(WP_Term)#3878 (16) { ["term_id"]=> int(39) ["name"]=> string(14) "ВИДЕНИЯ" ["slug"]=> string(42) "%d0%b2%d0%b8%d0%b4%d0%b5%d0%bd%d0%b8%d1%8f" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(39) ["taxonomy"]=> string(8) "category" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(3) ["filter"]=> string(3) "raw" ["cat_ID"]=> int(39) ["category_count"]=> int(3) ["category_description"]=> string(0) "" ["cat_name"]=> string(14) "ВИДЕНИЯ" ["category_nicename"]=> string(42) "%d0%b2%d0%b8%d0%b4%d0%b5%d0%bd%d0%b8%d1%8f" ["category_parent"]=> int(0) } }
  • Can you do var_dump($ar) and add the output to your question? – Emil Dec 14 '16 at 13:03
  • updated the question with output of var_dump($ar); – Orek Dec 14 '16 at 15:59
  • You're running a loop inside a loop, so it's going to print the categories for each post. What is your intended result? – Milo Dec 14 '16 at 16:35
  • 1
    The PHP function array_unique() does not work with Objects since it compares values. A post should not have duplicate categories returned so I'm not sure what you're trying to achieve here. – Howdy_McGee Dec 14 '16 at 17:00
  • This code is in author page and I'm trying to get all main categories that author posted a post in. – Orek Dec 14 '16 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.