如何获取父母和祖父母类别

时间:2016-05-04 作者:550

我想知道你如何才能收到我写的面包屑的类别父名称和链接。

我基本上希望有以下结构

if child category
blog > parent_category

else if grandchild category
blog > grand_parent_category > parent_category

2 个回复
最合适的回答,由SO网友:Ahed Eid 整理而成

此查询将帮助您

global $wpdb;

$cat_id = 65;

// this query will get parent relationships from term_taxonomy table and get category names from terms table
$category = $wpdb->get_row(
    "SELECT t4.term_id as parent_id, t4.name as parent_name, t5.term_id as grandparent_id, t5.name as grandparent_name FROM `{$wpdb->prefix}term_taxonomy` t1
left join `{$wpdb->prefix}term_taxonomy` t2 on t2.term_id = t1.parent
left join `{$wpdb->prefix}term_taxonomy` t3 on t3.term_id = t2.parent
left join `{$wpdb->prefix}terms` t4 on t4.term_id = t2.term_id
left join `{$wpdb->prefix}terms` t5 on t5.term_id = t3.term_id
where t1.term_id={$cat_id}"
);

if ($category->grandparent_id) {
    echo "blog > {$category->grandparent_name}  > {$category->parent_name}";
} else if ($category->parent_id) {
    echo "blog > {$category->parent_name}";
}

SO网友:550

Ok设法让孩子和家长正确循环。

$catid = get_query_var( \'cat\' );

while( $catid ) {
    $cat = get_category( $catid ); // Get the object for the catid.
    $catid = $cat->category_parent; // assign parent ID (if exists) to $catid
    // the while loop will continue whilst there is a $catid
    // when there is no longer a parent $catid will be NULL so we can assign our $catParent
    $category_parent = $cat->cat_name;
    $category_parent_link = get_category_link( $cat->cat_ID );

    echo \'<li class="\' . esc_attr( $root_item_class ) . \'" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem" aria-level="3"><a href="\' . esc_url( $category_parent_link ) . \'" itemprop="item"><span itemprop="name">\' . $category_parent . \'</span></a><meta itemprop="position" content="3" /></li>\';
}
现在的问题是,我需要反转循环的输出,因为它当前正在循环。

child > parent > grandparent
如果存在。

此外,在循环的每个阶段,我都需要为模式和可访问性逻辑添加正确的值。根据祖先的数量,每个等级需要增加1。

例如

<meta itemprop="position" content="3" /> AND aria-level="3" by each level.
有伟大的祖父母【3】>祖父母【4】>父母【5】等。