Ben Daggers
Ben Daggers

Reputation: 992

Show Parent & 1st Level CHILD Category in a Drop Down List Wordpress

I currently have this code that shows all the parent categories in a drop down list.

HTML/PHP Code

<ul>
    <?php 
    $args = array(
    'orderby' => 'name',
    'hierarchical' => 1,
    'taxonomy' => 'category',
    'hide_empty' => 0,
    'parent' => 0,
    );
    $categories = get_categories($args);
    foreach($categories as $category) {
    echo '<li><a href="' . get_category_link($category->cat_ID) . '" title="' . $category->name . '">' . $category->name . '</a></li>';
    } 
    ?>
</ul>

There's no problem with the code below. Actually, it works perfectly! You can see it here at my wordpress website: www.bendaggers.com

What I want to achieve now is how can I add the 1st level child of the parent just what it shown in Image 1 below with the same effect.

Image 1 - Sample

This is what I want to achieve, whenever the user hovers on the listed Parent Category, it will display its 1st level child category as show in the image below.

enter image description here

Image 2 - Sample Parent/Category Hierarchy.

enter image description here

By the way, I need a working code PHP, HTML and CSS also.

I really appreciate you help and efforts, thank you very much!

Some additional Information that might be useful.

Upvotes: 7

Views: 2636

Answers (3)

Ujjwal
Ujjwal

Reputation: 529

Did you refer wordpress function wp_nav_menu?

You can visit here for wordpress nav,

https://codex.wordpress.org/Function_Reference/wp_nav_menu

And here is the guide for multiple level menus.

https://codex.wordpress.org/WordPress_Menu_User_Guide

Upvotes: 0

Hareesh Sivasubramanian
Hareesh Sivasubramanian

Reputation: 1260

Take a look at wp_list_categories() function. Replace the entire code that you've provided here with this. wp_list_categories(array('title_li' => '')); Add this to the stylesheet.

.cat-item {
    list-style-type: none;
    position: relative;
}
.cat-item .children {
    display: none;
    position: absolute;
    top: 0;
}
.cat-item:hover > .children {
    display: block;
}

Upvotes: 0

Jagdish Banda
Jagdish Banda

Reputation: 62

You can make function for check If the parent category has child category and pass parent term into newly created function. copy your ablove code and make a function and paste it in your custom function.

And get parent category(you should make first custom function to get paent term) and pass this term to your second custom function

Upvotes: 2

Related Questions