0

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;  
      ?>

1 Answer 1

3

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

0

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.