• I’d like to use a dynamic sidebar that includes one custom menu. I’m able to add pages to the custom menu as well as “custom” links. One of the “custom” links I’d like to add, when clicked, doesn’t point to a URL but rather calls a js function (i.e. if writing the code for the sidebar by hand, it would be href=”javascript:function_name();”).

    Custom menus does not, however support this; as the href doesn’t begin with “http://” it automatically deletes the function call.

    One workaround is to edit sidebar.php as follows:

    <ul>
    	<li><a href="javascript:function_name();">Anchor Text</a></li>
            <?php if ( function_exists('dynamic_sidebar') && dynamic_sidebar(1) ) : else : ?>
            <?php wp_list_pages('title_li=&hierarchical=0'); ?>
            <?php endif; ?>
            </ul>

    This will display the desired function call link first, and then the rest of the custom menu. However, it sees the dynamic menu as a “child” of the first

    • set, and indents the entire menu, as opposed to lining it up on the left directly under the first hand-coded
    • with the function call.

      What would be the best way to achieve this?

      Thanks!

Viewing 1 replies (of 1 total)
  • Faced with the same requirement, in the Appearance -> Menus interface I added javascript to the link descriptions where needed. (I was able to re-purpose the description field because I wasn’t using it for any other reason. If I were, I could have added “javascript:” to the start of the description). Then I added a custom walker to replace the href and onclick attributes for each link containing a description. The relevant part of the walker follows:

    // HACK ATTACK! descriptions default to a single space
    if (strlen($item->description)>2) {
          $attributes .= ' href="javascript:;" onclick="'. esc_attr( $item->description ) .'"';
    } else {
          $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url            ) .'"' : '';
    }

    You can find how to add and call custom walkers elsewhere. Good luck.

Viewing 1 replies (of 1 total)

The topic ‘Javascript in Custom Menus?’ is closed to new replies.