Add a link wrapper to 1 dropdown menu in WordPress

So, I’ve created a custom walker class allowing me to wrap my dropdown menu items in a container so that I can add a custom background, and control the styling. Long list of reasons, why, it was just decided among my team and I that we do it that way. However, the dropdown on ONE element needs to now be wrapped in an a tag to link to a sponsor. Granted I can manipulate the custom Walker, but that would add the link to all of the elements that’s targeted.

So what I want to know is if it is possible to just target the ONE dropdown I need. Let’s say it’s li#menu-item-18

Read More

Here is my custom Walker code

class My_Custom_Walker_Class extends Walker_Nav_Menu {
    function start_lvl( &$output, $depth ) {
            $indent = ( $depth ) ? str_repeat( "t", $depth ) : '';

            $output .= $indent . '<ul class="sub-menu"><div class="sub-menu-child">';
    }
    function end_lvl( &$output, $depth ) {
            $indent = str_repeat("t", $depth);
            $output .= $indent . '</div></ul>';
    }
}

/**
 * Add the Menu_With_Data_Attr walker to the wp_nav_menu() used by genesis_do_nav()
 */

add_filter( 'wp_nav_menu_args', function( $args ){
    if( isset( $args['menu_class'] ) && 'menu genesis-nav-menu menu-primary' === $args['menu_class'] ) {
            if( class_exists( 'My_Custom_Walker_Class' ) ) {
                    $args['walker'] = new My_Custom_Walker_Class();
            }
    }
    return $args;
});

Related posts

Leave a Reply

1 comment

  1. You could re-define the start_el method of the parent class in your custom class, but that seems a lot of code to duplicate for a minimal change (I don’t like it).

    A better solution is to use the filter hook at the end of the parent method, walker_nav_menu_start_el, to add a wrapper only for the item you want, like this:

    add_filter('walker_nav_menu_start_el', function($item_output, $item, $depth, $args){
    
        if( 18 == $item->ID && 'menu genesis-nav-menu menu-primary' === $args['menu_class'] )
    
            return sprintf('<div class="targeted">%s</div>', $item_output);
    
        return $item_output;
    
    }, 10, 4);
    

    Change the wrapper div with what you prefer.