Support » Developing with WordPress » Output the same parent category title once

  • Resolved palmtree


    Hello codemaster,

    I want to output category title only once even under the following situation.

    Category X is a child category of A (A is a parent cat of X). In the post editing page of the WordPress when I select parent category “A” as well as the direct category of the post, “X”, before publishing. The following code outputs cat title A → A → X. Notice cat name “A” is output twice.

    If I don’t select the parent category “A” but only “X” before publishing post, the cat title output will be correct which is A → X. “A” isn’t output twice.

    My code is below..

    is_singular('post') {
        $categories = get_the_category();
        echo '<h2>';
        foreach ($categories as $cat) {
            echo get_category_parents($cat, true, '<span class="category-separator">&nbsp;&rarr;&nbsp;</span>');
        echo '</h2>';

    It would be fantastic if you could give me advise.

    Thank you.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz


    Try using the “get_ancestors” filter. Apply array_unique() to the passed array to remove duplicate terms. This will affect any function anywhere in your site that uses the get_ancestors() function, which is what get_category_parents() uses. You may need to use a conditional to ensure the filter is only applied to the correct situation. The filter passes several values that may be useful, the object ID, object type, and resource type.

    You can try below code to show category of a post.
    It will not duplicate your parent category.

    * Show all category that belongs to a post
    * not show all category of wordpress 
      $aa = get_the_terms(get_the_ID(), 'your_post_taxonomy_name');
    <?php foreach($aa as $bb): ?>
      <a href="<?php echo get_term_link($bb->term_id) ?>">
        <?php echo $bb->name; ?>
    <?php endforeach; ?>

    Let me know about your status.

    Thanks guys for your advise,

    I have put following code to achieve what I wanted and it worked:)

    $cats = get_the_category();
    $cat = $cats[0];
    if ($cat->parent){
      $parent = get_category($cat->parent);
      echo '<h2><a href="' . get_category_link($cat->cat_ID) . '">' . $parent->cat_name . '</a>';
    } else {
      echo '<h2><a href="' . get_category_link($cat->cat_ID) . '">' . $cat->cat_name . '</a>';
    $cats = get_the_category();
    foreach($cats as $cat):
      if($cat->parent) echo '<span class="category-separator">&nbsp;&rarr;&nbsp;</span><a href="' . get_category_link($cat->cat_ID) . '">' . $cat->cat_name . '</a>';
      echo '</h2>';
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Output the same parent category title once’ is closed to new replies.