首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何调整此代码以包含子类别?Wordpress / Woocommerce

如何调整此代码以包含子类别?Wordpress / Woocommerce
EN

Stack Overflow用户
提问于 2021-05-12 02:36:43
回答 1查看 29关注 0票数 1

我在一个旧的overflow帖子上找到了这个代码,它帮助我在打开某个产品后返回到主要产品类别:

代码语言:javascript
复制
add_action ('woocommerce_before_single_product','add_back_product_category_button', 5);
function add_back_product_category_button(){

    // Get the product categories set in the product
    $terms = wp_get_post_terms( get_the_id(), 'product_cat' );

    // Check that there is at leat one product category set for the product
    if(sizeof($terms) > 0){
        // Get the first product category WP_Term object
        $term = reset($terms);
        // Get the term link (button link)
        $link = get_term_link( $term, 'product_cat' );

        // Button text
        $text = __('Voltar a','woocommerce') . ' <strong>' . $term->name . '</strong>';

        // Output
        echo '<p><a href="'.esc_url($link).'" title="'.$text.'" class="button '.$term->slug.'">'.$text.'</a></p>';
    }
}

虽然这段代码非常有用,但我觉得有必要让我的客户在返回主类别之前能够返回子类别。

每个示例:

当我的客户访问类别“女人”,然后是子类别“裙子”,他们可以返回到“女人”没有问题。当我的客户访问“短剧”中的某个产品时,这个问题就会出现。在产品页面中,如果他们点击代码创建的后退按钮,他们会转到“女人”,而不是“裙子”。

所以,客户是在:女人-> Skirts ->产品他们应该回到Skirts,而不是在她们点击代码的时候创建back按钮。

我希望这已经足够清楚了!

干杯

EN

回答 1

Stack Overflow用户

发布于 2021-05-12 03:40:13

您可以通过get_term_parents_list()检索特定的术语parent。

检索带分隔符的父项。

代码语言:javascript
复制
<?php

$term = reset( wp_get_post_terms( get_the_id(), 'product_cat' ) );

$args = array(
    'format' => 'name',
    'link' => true,
    'inclusive' => false,
);
  
echo get_term_parents_list( $term->term_id, $term->taxonomy, $args );

我不能测试它,但它应该可以在壁虎上工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67492544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档