Home Ask Login Register

Developers Planet

Your answer is one click away!

Ochab February 2016

Insert hash into url to turn it into an anchor

I'm using Wordpress, and trying to figure out how to hack the links within the sub-menus.

I've set up a demo here: http://brandsite.simpletruth.io/logo/

Specifically, I want to add a hash in front of second-level menu links so that they become same-page anchors instead of going to a separate page.

For instance:

http://brandsite.simpletruth.io/logo/logo-spacing/

Becomes:

http://brandsite.simpletruth.io/logo#logo-spacing

Ideally this happens within Wordpress, but I think doing it with javascript would be an okay solution too.

Thanks!

Answers


Mark February 2016

you have to use a custom walker function

in your instance:

in your functions

class custom_names extends Walker_Nav_Menu
    {

        /* Start of the <ul>
         *
         * Note on $depth: Counterintuitively, $depth here means the "depth right before we start this menu".
         *                 So basically add one to what you'd expect it to be
         */
        function start_lvl(&$output, $depth = 0, $args = array())
        {
            $indent = str_repeat("\t", $depth);
            $output .= "\n$indent<ul class=\"children\">\n";
        }

        /* End of the <ul>
         *
         * Note on $depth: Counterintuitively, $depth here means the "depth right before we start this menu".
         *                 So basically add one to what you'd expect it to be
         */
        function end_lvl( &$output, $depth = 0, $args = array() ) {
            $indent = str_repeat("\t", $depth);
            $output .= "$indent</ul>\n";
        }

        /* Output the <li> and the containing <a>
         * Note: $depth is "correct" at this level
         */
        function start_el( &$output, $item, $depth = 0, $args = array(),  $current_object_id = 0 )
        {
            $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

            $classes = empty( $item->classes ) ? array() : (array) $item->classes;
            $classes[] = 'menu-item-' . $item->ID;

            $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );

            $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
            $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';


            $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );
         

Post Status

Asked in February 2016
Viewed 2,398 times
Voted 7
Answered 1 times

Search




Leave an answer


Quote of the day: live life