Recursive PHP function for finding a top level parent post

June 5th, 2010 by Sean Leave a reply »

So… the name says it all doesn’t it! Here’s the story.. I wanted to apply different sidebar widget areas in Wordress for different pages.

One of the sites I am working on has three top level pages which will form three distinct sections of the site. I decided that it would be good to show different sets of widgets within these sections and therefore had to concoct a way to determine from any page it’s top level parent page. The function below simply returns true or false if the first argument is a child of the second. It also returns true if the first argument is the same as the second.

The Function

function page_has_parent($current_page, $target_parent=0) {
	global $wpdb;

	$return = false;

	if ($current_page == $target_parent) {
		$return = true;
	} else {
		$sql = 'SELECT post_parent
			FROM ' . $wpdb->posts . '
			WHERE ID = ' . $current_page;
		if ($parent = $wpdb->get_var($sql)) {
			if ($parent == $target_parent) {
				$return = true;
			} else if ($parent) {
				$return = page_has_parent($parent, $target_parent);
			}
		}
	}

	return $return;
}

The Usage

The following is a WordPress example of showing one sidebar or the other based on page

$this_page = get_the_ID();
if (page_has_parent($this_page, 7)) {
	dynamic_sidebar('Sidebar2');
} else if (page_has_parent($this_page, 11)) {
	dynamic_sidebar('Sidebar2');
} else ....

Leave a Reply