Search code examples
wordpressdrop-down-menumenuhtml-select

Change selected drop down option depending on page (menu)


I'm using a dropdown menu in my WP theme, with the use of select boxes. With the help of some jQuery the page changes when a new select option is chosen. However, when the new page is rendered the default option in the select menu is still "Start page" (the first one).

What can I do to make that one change to the current page?

header.php:

<div id="navigation" role="navigation">

    wp_nav_menu(array(
        'container' => false,
        'menu_id' => 'nav',
        'theme_location' => 'primary', // your theme location here
        'walker'         => new Walker_Nav_Menu_Dropdown(),
        'items_wrap'     => '<select>%3$s</select>',
        'fallback_cb'    => 'bp_dtheme_main_nav'
    ));


    class Walker_Nav_Menu_Dropdown extends Walker_Nav_Menu{
        function start_lvl(&$output, $depth){
            $indent = str_repeat("\t", $depth);
            }

        function end_lvl(&$output, $depth){
            $indent = str_repeat("\t", $depth);
        }

        function start_el(&$output, $item, $depth, $args){
            $item->title = str_repeat("&nbsp;- ", $depth).$item->title;

            parent::start_el($output, $item, $depth, $args);

            $href =! empty( $item->url ) ? ' value="'   . esc_attr( $item->url ) .'"' : '#';

            $output = str_replace('<li', '<option '.$href, $output);
        }

        function end_el(&$output, $item, $depth){
            $output .= "</option>\n"; // replace closing </li> with the option tag
        }
    } ?>

</div>

jquery:

$("#navigation select").on('change', function() {
    window.location = jq(this).find("option:selected").val();
});

Solution

  • Since the value of each option is a URL, just loop through each option and compare to the current page URL. If they're the same, set the option's property to selected.

    $("#navigation option").each(function () {
        if ($(this).val() === window.location.toString()) {
            $(this).prop('selected', true);
        }
    });