Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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>';
}
?>
share|improve this question
    
Why are you querying for posts if you want categories? –  t31os Aug 16 '11 at 23:11
    
to get the categories to show, they wont show unless they have post inside them correct? –  user7924 Aug 16 '11 at 23:18
    
I'm not sure i follow... do you need a list of posts or categories, or both? –  t31os Aug 16 '11 at 23:19
1  
get_categories would probably be more suitable for your use. –  t31os Aug 16 '11 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 Aug 17 '11 at 9:07

2 Answers 2

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

share|improve this answer

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>';
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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