If you want this for pages only, which would makes sense as to what you described this, just wrap the whole bunch of code in if ( is_page() ) { ... }
.
If you were to put this into a function, you could just bail out early.
function wpdev_156446_list_parent_page_tree() {
if ( ! is_page() ) {
return;
}
// Your above code here
}
// EDIT
function wpdev_156446_list_parent_page_tree() {
if ( ! is_page() ) {
return;
}
$parent = get_post($post->post_parent);
$parent_title = get_the_title($parent);
$grandparent = $parent->post_parent;
$grandparent_title = get_the_title($grandparent);
$current_page_parent = ( $post->post_parent ? $post->post_parent : $post->ID );
// is the homepage the granparent? = third level page
if ($grandparent == is_page('0')) {
$children = wp_list_pages("title_li=&include=".$post->post_parent."&echo=0"); // list the parent page
$children .= wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); // append the list of children pages to the same $children variable
if ($children) {
?>
<ul class="submenu">
<?php echo $children; /*print list of pages*/ ?>
</ul>
<?php
}
// is the homepage the parent? = second level page
} elseif ($post->post_parent ==is_page('0')) {
$children = wp_list_pages('title_li=&child_of=".$post->ID."&echo=0');
if ($children) {
?>
<ul>
<li class="current_page_item"><?php echo get_the_title(); ?></li>
<?php echo $children; ?>
</ul>
<?php
} else {// your else stuff
}
}
}