WordPress.org

Ready to get started?Download WordPress

Forums

How get ALL parent category in post? (2 posts)

  1. stili
    Member
    Posted 4 years ago #

    Hi All,

    How get ALL parent category in post? (category list from post category to child)

    for example:

    Main - News - My_news - This_post_category

    Big thanks

  2. MichaelH
    Member
    Posted 4 years ago #

    <?php
    //display parent categories for each category on a post--must be used in the loop
    $cats = get_the_category();
    if ($cats) {
      foreach($cats as $cat) {
        $parents = array();
        $have_parents = false;
        $parent_id = $cat->category_parent;
        while (0 != $parent_id) {
          $parents[]=$parent_id;
          $next_ancestor = get_category( $parent_id );
          $parent_id = $next_ancestor->category_parent;
        }
        if ($parents) {
          echo 'parents';
          foreach ($parents as $parent) {
            $category = get_term_by('ID',$parent, 'category');
            echo '<p><a href="' . esc_attr(get_term_link($category, 'category')) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a><p> ';
          }  //foreach ($parents
        }
      } //foreach ($cats
    }
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags