get_ancestors()
seems like the function you need. If given an ID and object type, it will return an array of ancestor IDs with the first being the most distant parent/grandparent/great-grandparent/etc and the last being the immediate parent. You can use that information to construct your link.
function parent_id_wpse_142550($object_id,$type) {
$anc = get_ancestors($object_id,$type);
$parent = array_shift($anc);
if (!empty($parent)) {
return $parent;
} else {
return false;
}
}
function parent_link_wpse_142550($link) {
if (!is_wp_error($link)) {
return '<h2 class="link"><a href="'.$link.'">Return</a></h2>';
}
}
function parent_term_link_wpse_142550($object_id,$type) {
$parent = parent_id_wpse_142550($object_id,$type);
if(!empty($parent) && $parent != 1){
$link = get_term_link($parent,$type);
return parent_link_wpse_142550($link);
}
}
function parent_cpt_link_wpse_142550($object_id,$type) {
$parent = parent_id_wpse_142550($object_id,$type);
$link = get_page_link($parent,$type);
return parent_link_wpse_142550($link);
}
function make_links_wpse_142550($content) {
$links="";
global $post;
$links .= parent_cpt_link_wpse_142550($post->ID,'book');
$terms = get_the_terms($post->ID, 'genre');
if (!empty($terms)) {
$term_id = array_shift($terms)->term_id;
$links .= parent_term_link_wpse_142550($term_id,'genre');
}
return $links.$content;
}
add_filter('the_content','make_links_wpse_142550');