get_ancestors()
似乎是你需要的功能。如果给定ID和对象类型,它将返回一个祖先ID数组,第一个是最远的父/祖/曾祖/曾祖/等,最后一个是直系父。您可以使用这些信息构建链接。
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\');