1

I'd like to automatically make any parent page link to it's first subpage if it has one. Like so:

  • Parent 1 (/#subpage-1)
    • Subpage 1 (/#subpage-1)
    • Subpage 2 (/#subpage-2)
    • Subpage 3 (/#subpage-3)
  • Parent 2 (/parent-2)
  • Parent 3 (/parent-3)

I found some code that finds all the parent links through a complicated nav() walker. From here I'm not sure how to find the first childs url. I assumed it would be

$children_elements[0]->url

but it doesn't seem to be the case.

class Themeslug_Page_Navigation_Walker extends Walker_Nav_Menu {
    function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {
        $id_field = $this->db_fields['id'];
        if ( !empty( $children_elements[ $element->$id_field ] ) ) {
            $element->url = "Where do I get the child URL?";
        }
        Walker_Nav_Menu::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
}

1 Answer 1

1
class Themeslug_Page_Navigation_Walker extends Walker_Nav_Menu {
    function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {
        $id_field = $this->db_fields['id'];
        if ( !empty( $children_elements[ $element->$id_field ] ) ) {
            $element->url = $children_elements[$element->$id_field][0]->url;
        }
        Walker_Nav_Menu::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
}

This did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.