how to show grandchildren in wordpress navigation
So you think you’ve got navigation covered in wordpress, a dash of wp_list_pages here and there and everything is covered. You start to work on a theme that has 3 sets of navigation in different areas and you think it’s simple! Ever tried showing grandchildren in wordpress?
Not entirely sure what the problem is as I’ve not had time to investigate fully, but here is the scenario:
- Have a theme that has a top layer of navigation, easily sorted with wp_list_pages.
- On entering sub pages, siblings are shown on a second layer of navigation underneath the first one, again, quite straightforward.
- On drill down to grandchil page, another navigation panel is revealed to show other grandchildren siblings, should be simple enough to work, but doesn’t, the ‘child_of’ argument on wp_list_pages produces no output.
After trying so may different methods suggested on so many websites (in an attempt to get a quick solution), found I had to resort to a custom query to get it sorted:
$page = get_second_topmost_parent($post->ID); $querystr = "SELECT wposts.* FROM $wpdb->posts wposts WHERE wposts.post_status = 'publish' AND wposts.post_type = 'page' AND wposts.post_parent = $page ORDER BY wposts.post_date DESC"; $pageposts = $wpdb->get_results($querystr, OBJECT); if ($pageposts) { foreach ($pageposts as $post) { setup_postdata($post); echo "<li>" . get_the_title() . "</li>"; } }
Excuse the mess, but it will show 3rd level siblings (grandchildren) on an unordered list, should be simple enough to implement on your own website. This solution makes use of a custom function that find the id of the parent page and shows its children:
function get_second_topmost_parent($post_id){ $post = get_post($post_id); // get post data $parent_post_id = $post->post_parent; // get posts parent $second_post = get_post($parent_post_id); get post data of parent $second_parent_post_id = $second_post->post_parent; // get parent of parent if ($second_parent_post_id == 0){ // if parent of parent has root id of 0, current page is a grandchild, return id return $post_id; } else { return get_second_topmost_parent($second_parent_post_id); } }
Tags: grandchildren, themes, wordpress
Leave a Reply