• lobaath

    (@lobaathhotmailcom)


    Hi Could anybody help me solve this little dilemma.

    I want to list post category, but if the post is in category 3, then list the children of that cat. Check my code out below.

    <?
    $categories = get_the_category();
    $creative_field = array();
    $location = array();
    $auktion = array();
    
    foreach ($categories as $cat) {
      if ($cat->parent == 3) { //Formgivare
        $creative_field[] = '<a>cat_ID).'" title="'.$cat->cat_name.'">'.$cat->cat_name.'</a>';
      } else if($cat->parent == 1){ //Samlare
        $location[] = '<a>cat_ID).'" title="'.$cat->cat_name.'">'.$cat->cat_name.'</a>';
      }	else if ($cat->parent == 16){ //Auktion och alla andra
        $auktion[] = '<a>cat_ID).'" title="'.$cat->cat_name.'">'.$cat->cat_name.'</a>';
      }
    }
    
    if(!empty($creative_field)){
      print "". implode(", ",$creative_field);
    }
    
    if(!empty($location)){
      print "". implode(", ",$location);
    }
    
    if(!empty($auktion)){
      print "". implode(", ",$auktion);
    }
    
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter lobaath

    (@lobaathhotmailcom)

    Or if someone has a better idea, to get post category (only parent) but if cat got children, get (only child cat)?

    Moderator bcworkz

    (@bcworkz)

    get_the_category() will only return terms assigned to the current post, whether they are children or not. What you do with that information is up to you. You can use get_term_children() with each term to get any children if they exist. If there are no children I believe it returns an empty array (verify). Something like this(untested):

    $cats = get_the_category();
    foreach( $cats as $cat ) {
       $children = get_term_children( $cat->term_id, 'category');
       if ( 0 == count( $children )) { // no children
          $output[] = $cat->name;
       } else { // there are children
          foreach( $children as $child ) {
             $term = get_term_by( 'id', $child, 'category');
             $output[] = $term->name;
          }
       }
    }

    This example is deficient in that there is no error checking and a 0 count is ambiguous, but illustrates the concept. You would want different output no doubt as well. This also does not care if the post’s terms are top level or children with children, only that the term has children.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘If "this" category has children, show them other wise show parent’ is closed to new replies.