代码之家  ›  专栏  ›  技术社区  ›  Alex

Woocommerce在单个产品上获取父slug/name。php

  •  0
  • Alex  · 技术社区  · 8 年前

    我知道之前有人问过关于woocommerce和获取父类别的问题。我已经对堆栈溢出做了很多研究,发现了很多与我试图实现的简单性不符的答案。

    基本上我有我的单一产品。php页面,我们有一个网站,它需要不同的页眉/页脚和基于产品所属类别的设计。

    为了实现这一点,我们只需要访问父类别的名称,这样我们就可以指定它应该加载的页眉/页脚。

    我确实找到了 this on wordpress.stackexchange ,但它对于我的需要来说太复杂了,所以我尝试剥离一些代码,并将其直接放在单个产品中。php页面如下:

    global $post;
    
    $descendant = get_the_terms( $post->ID, 'product_cat' );
    $descendant = array_reverse($descendant);
    $descendant = $descendant[0];
    $descendant_id = $descendant->term_id;
    $ancestors = array_reverse(get_ancestors($descendant_id, 'product_cat'));
    $ac = count($ancestors);
    $c = 1;
    $origin_ancestor_term = get_term_by("id", $ancestors[0], "product_cat");
    $origin_ancestor_term->name;
    
    $headername = $origin_ancestor_term->name;
    
    
    if ($headername == 'Events') {
        $productparentcat = 'events';
    } else {
        $productparentcat = 'adventures';
    }
    
    get_header($productparentcat);
    

    奇怪的是,在我更新wordpress版本之前,这似乎在我的本地版本上起作用,然后它就坏了。我现在还收到以下错误:

    Notice: Undefined offset: 0 (for $c = 1;)
    Notice: Trying to get property of non-object (for the $origin_ancestor_term->name;)
    

    有没有人知道一种简单的方法可以在单个产品模板上检索父类别名称?我看过很多标准wordpress函数来实现这一点,但它们不适用于woocommerce模板,我想是因为它们使用自定义分类法。。。

    非常感谢。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Alex    8 年前

    在进一步研究这个问题后,我意识到答案非常简单,主要问题是我在错误的地方寻找解决方案。

    我一心想找到产品的类别父ID/名称,但事实上,网站上的所有产品都包含在子类别和父类别下。

    例如,一款名为“嘉年华特别版”的产品同时位于“嘉年华”和“福特”之下,因此,如果我试图使用产品ID搜索类别“嘉年华”的父项,它就不起作用,因为它也在寻找“福特”的父项,而这是最高级别的类别。

    这就是导致我在“注意:未定义的偏移量:0(对于$c=1;)”方面出错的原因。

    最后我用了这个:

    if ( has_term('Ford', 'product_cat', null) ) {
        get_header('ford');
    } else {
        get_header('other-makes');
    }
    
    
    
    $carclass = '';
    
    if(has_term('Ford', 'product_cat', $post)) {
        $carclass = 'ford';
    } else {
        $carclass = 'other-cars';
    }
    

    这使我能够根据是否勾选了特定类别来设置页面样式并拉入右侧标题。