Making breadcrumb with wp_nav_menu

I couldn’t believe there is not a single FREE plugin available that does this. So I wrote my own function. Here you go. Just copy this to your functions.php:

function my_breadcrumb($theme_location = 'main', $separator=" > ") {
    
    $theme_locations = get_nav_menu_locations();
    
    if( ! isset( $theme_locations[ $theme_location ] ) ) {
        return '';
    }
    
    $items = wp_get_nav_menu_items( $theme_locations[ $theme_location ] );
    _wp_menu_item_classes_by_context( $items ); // Set up the class variables, including current-classes
    $crumbs = array();

    foreach($items as $item) {
        if ($item->current_item_ancestor || $item->current) {
            $crumbs[] = "<a href=\"{$item->url}\" title=\"{$item->title}\">{$item->title}</a>";
        }
    }
    echo implode($separator, $crumbs);
}

Then, anywhere in your theme you can output the breadcrumb like this:

<?php my_breadcrumb('menu-slug'); ?>

This code can easily be extended, by omitting the $theme_location parameter and getting a list of every available menu, only outputting the result if the $crumbs array isn’t empty. I may write a blog post about this or turn it into a free plugin soon. Keep you updated.

You could also add a class or differnt markup the current item by checking for $item->current.

Leave a Comment