WordPress.org

Ready to get started?Download WordPress

Forums

How to get top-level parent Pages? (5 posts)

  1. Parhelion
    Member
    Posted 4 years ago #

    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?

  2. SpankMarvin
    Member
    Posted 4 years ago #

    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");
    		wp_list_pages($args);
    		echo("</ul>\n</div>");
    }

    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

    J

  3. afonsojr
    Member
    Posted 3 years ago #

    $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.

  4. arthurattwell
    Member
    Posted 3 years ago #

    @afonsojr Thanks, that worked perfectly for me.

  5. Zach "The Z Man" Abernathy
    Member
    Posted 3 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.