1

I'd like to list my categories in a loop from a-z, the code i currently have just keeps repeating over and over im not sure what the problem is but the format should look something like.

  • Parent Category

    • Child Category
    • Child Category
    • Child Category
    • Child Category

My code:

<?php 
$args = array( 'orderby' => 'name','order' => 'ASC' );
$categories = get_categories( $args );
foreach($categories as $category) {
    echo '<p><a href="'.get_category_link( $category->term_id ).'">'.$category->category_nicename.'</a></p>';
    echo '<p class="cat-child"><a href="'.get_category_link( $category->term_id ).'">'.$category->child.'</a></p>';
}
?>
7
  • Why are you querying for posts if you want categories?
    – t31os
    Commented Aug 16, 2011 at 23:11
  • to get the categories to show, they wont show unless they have post inside them correct?
    – user7924
    Commented Aug 16, 2011 at 23:18
  • I'm not sure i follow... do you need a list of posts or categories, or both?
    – t31os
    Commented Aug 16, 2011 at 23:19
  • 1
    get_categories would probably be more suitable for your use.
    – t31os
    Commented Aug 16, 2011 at 23:31
  • 1
    I'm still struggling to follow, based on the example format you've shown, Gavin's answer should address your needs, if not please clarify more.
    – t31os
    Commented Aug 17, 2011 at 9:07

3 Answers 3

3

So you want to list the categories in a tree structure, in alphabetical order, showing ALL categories (even empty ones)? If so, try this:

<?php
    $args = array('orderby' => 'name', 'order' => 'ASC', 'hide_empty' => false);
    $categories = wp_list_categories($args);
?>

Reference: wp_list_categories

1

Try this:

//get only parents
$args = array('orderby' => 'name','order' => 'ASC','parent' => 0);
$Parent_categories = get_categories($args);

foreach($Parent_categories as $category) { 
    echo '<p><a href="'.get_category_link( $category->term_id ).'">'.$category->category_nicename.'</a><br/>';
    //get all children of this category
    $args = array('orderby' => 'name','order' => 'ASC','parent' => $category->term_id);
    $Child_categories = get_categories($args);
    foreach ($Child_categories as $c){
        echo '<span class="cat-child"><a href="'.get_category_link( $c->term_id ).'">'.$c->category_nicename.'</a></span>  ';
    }
    echo '</p>';
}
0

You can get & list all categories, with sub-categories, like a "tree"! see solution:
How to sort list of custom posts to get view like a tree of posts under categories and their children's categories?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.