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 am trying to do two things, which I have no idea how to do:

  1. give child categories the same class as the parent category (which is the parent category-slug)

  2. create a menu which displays my categories, where the child categories will be displayed as dropdown-items when hovering the parent categor

Currently I am using this code to generate the classnames for my categories, and create my menu:

<?php
    $args = array(
        'hide_empty'               => 0
     );
       $categories = get_categories($args); 
    $menu = '<ul class="nav">';
    // iterate through your categories
    foreach($categories as $category) { 
        $menu .= '<li class="' . 'cat-item category-' . $category->slug . '">' . '<a href="'.get_category_link($category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">' . $category->cat_name . '</a>' . '</li>'   
    }  
    $menu .= '<li class="menu-border">' . '</li>' . '</ul>';
    echo $menu;  
      ?>
share|improve this question

1 Answer 1

up vote 3 down vote accepted

If you want only 2 levels, you may use the parent parameter. Example

<?php
$args = array(
    'hide_empty' => 0,
    'parent' => 0
);
$categories = get_categories($args); 
$menu = '<ul class="nav">';
// iterate through your categories
foreach($categories as $category) { 
    $menu .= '<li class="' . 'cat-item category-' . $category->slug . '">' . '<a href="'.get_category_link($category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">' . $category->cat_name . '</a>';
    $children = get_categories( array('parent' => $category->term_id) );
    if($children && !empty($children)) {
        $menu .= '<ul class="subnav">';
        foreach ($children as $child) {
            $menu .= '<li class="' . 'cat-item category-' . $category->slug . '">' . '<a href="'.get_category_link($child->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $child->name ) ) . '">' . $child->cat_name . '</a></li>';
        }
        $menu .= '</ul>';
    }
    echo '</li>';
}  
$menu .= '<li class="menu-border">' . '</li>' . '</ul>';
echo $menu;  
?>

If you have unknown number of levels, you can implement a similar logic as a recursive function

share|improve this answer
    
Thank you so much! –  Cody Oct 20 '12 at 11:09

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.