固定ページの最上位親ページIDを取得する

wordpressの固定ページでは親子関係を作ることができる。
直接の親は$post->post_parentで取得できるが、最上位の親は直接取得するのが面倒。
ということで、functions.php

function get_top_parent_page_id() {
    global $post;
    $ancestors = $post->ancestors;
    if ($ancestors) {
        return end($ancestors);
    } else {
        return $post->ID;
    }
}

で、テーマファイルの中でget_top_parent_page_id($ID)で呼び出す。