Layer Navigation Function
-
For a project I needed to have separate layers of navigation on different parts in my template. Problem was that I didn’t want to have just the child pages of the current page, i needed a particular layer of navigation from the specific ‘branch’ of the current page.
I came up with the following function:
// Returns a specfic layer of the navigation relative to the root // and based on the 'branch' of the current page. // $layer is 1, would be the first layer of SUBNAVIGATION if ( !function_exists( 'get_ancestor_id' ) ) { function get_ancestor_id( $current_page_id, $layer ){ $ancestors_arr = get_post_ancestors( $current_page_id ); $ancestors_arr = array_reverse ($ancestors_arr); $ancestors_depth = count($ancestors_arr); if( $layer > 0 && $layer > $ancestors_depth ) { // The current page less deep dan de specified layer. if( $ancestors_depth - $layer == -1 ){ $menuroot_pageid = $current_page_id; } else { return false; } } else if ( $layer < 0 ) { // Set ancestor PageID relative to current page // e.g. -2 sets grandparent as menuroot_pageid; $index = $ancestors_depth + $layer; // results in something like 2 + (-1) which gets parents $menuroot_pageid = $ancestors_arr[ $index ]; } else { // Set ancestor PageID relative to root $menuroot_pageid = $ancestors_arr[ $layer - 1]; // -1 is correction } return $menuroot_pageid; } } if ( !function_exists( 'has_children' ) ) { function has_children($post_id) { $children = get_pages("child_of=$post_id"); if( count( $children ) != 0 ) { return true; } else { return false; } } }
In the theme you can acces a specific layer of navigation through:
<?php if ( $rootID = get_ancestor_id( $page_id, 1 ) ) : ?> <?php if ( has_children( $rootID ) ) : ?> <nav> <ul> <?php echo wp_list_pages("title_li=&child_of=". $rootID ."&echo=0&depth=1&sort_column=menu_order"); ?> </ul> </nav>< <?php endif; ?> <?php endif; ?>
I’d like to share this code with you, maybe it’s useful for someone. Besides that I’d like to know if anyone has any comments; and things by which I can improve.
Kind regards.
- The topic ‘Layer Navigation Function’ is closed to new replies.