获取当前类别的父类别以进行链接

时间:2019-09-24 13:56:59

标签: php wordpress woocommerce

在Woocommerce中,我试图在每个类别的父类别中添加一个“查看全部...”按钮。我在单个产品页面上完美地运行了它,因此尝试从那里修改代码。目前处于半工作状态,但我一直在努力使其正常工作,因为它总是分为3类,例如

照明>闪光灯>甚至在父级照明类别中的闪光灯套件。

有人可以指引我正确的方向吗?

    $product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );

if ( $product_cats && ! is_wp_error ( $product_cats ) ){
    $cat_depth = count($product_cats);
    echo $cat_depth;

    if ($cat_depth == 2)
    {$offset = 0;}
    else if ($cat_depth == 3)
    {$offset = 1;}

foreach (array_slice($product_cats,$offset) as $parent_cat){ ?>
    <h2 itemprop="name" class="product_category_title"><a href="<?php echo esc_url('/product-category/' .$parent_cat->slug ); ?>/"><span><i class="fas fa-th"></i> View all <?php echo $parent_cat->name ?></span></a></h2>
        <hr />

<?php break;}
}

1 个答案:

答案 0 :(得分:0)

尝试这个:

<?php
    $category = get_the_category(); 
    $category_parent_id = $category[0]->category_parent;
    if ( $category_parent_id != 0 ) {
        $category_parent = get_term( $category_parent_id, 'category' );
        $category_parent_link = get_category_link($category_parent->term_id);
    } else {
        $category_parent_link = get_category_link($category[0]->term_id);
    }

    foreach (array_slice($product_cats,$offset) as $parent_cat){

?>

       <h2 itemprop="name" class="product_category_title">
          <a href="<?= category_parent_link; ?>">
              <span>
                   <i class="fas fa-th"></i> View all 
                   <?= category_parent->name ?>
              </span>
          </a>
       </h2>
       <hr />

<?php 
     } 
?>
相关问题