Support » Fixing WordPress » How to get top-level parent Pages?

  • I’m working on a larger site that has multiple “departments” and I need a sub-menu that is unique to each ‘department’. For example, I have two departments – Cars and Movies. I need every page that would belong in Cars (Ford, Nissan, Honda) to have a relevant menu, while pages belonging in Movies will list different pages.

    The way I think I want to do this is to check the page to see if it has a parent. If so, the menu shown will be based on that parent (i.e, Cars or Movies). The problem is, I have no idea how to “crawl” all the way back to the highest level parent (and knowing this will be useful in creating breadcrumbs later on).

    What is the best way to do this?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Hey

    I recently had to do this for books. I made a function for the purpose:

    function list_car_subpages($id, $defs = 'title_li=&depth=1&sort_column=menu_order'){
    	$ancestors = get_post_ancestors($id);
    	$no_in_array = count($ancestors);
    	$lowest = $no_in_array - 1;
    	$next_in = $lowest - 1;
    	$lowest_parent = $ancestors[$lowest];
    		if($lowest == 0){ // Already the first in the array
    			$sub_parent = $id;
    		} else {
    			$sub_parent = $ancestors[$next_in];
    		$args = 'child_of=' . $sub_parent . '&' . $defs;
    		echo("<div id=\"car-sub-nav\" class=\"nav-item\">\n<ul>\n");

    Then create a page template for the sub-pages, and call function list_car_subpages($post->id). You can also define custom arguments to override the function’s defaults. Let me know if that helps, or is at least a starting point to get you on your way.

    Good luck




    $parent = array_reverse(get_post_ancestors($post->ID));
    $first_parent = get_page($parent[0]);
    echo $first_parent->post_name;

    With it will always take the first parent.
    I hope being helpfull.

    @afonsojr Thanks, that worked perfectly for me.

    @afonsojr Thanks a ton. That worked out just dandy.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to get top-level parent Pages?’ is closed to new replies.