【问题标题】:woocommerce category depth as condition with if statementwoocommerce类别深度作为if语句的条件
【发布时间】:2018-10-28 19:07:33
【问题描述】:

我不确定在这里进行的最佳方式。

我有这样的分类(简化版):

-fruit
--apple
---large
---small

--banana
---var1
----large
----small
---var2
----small
----large

我想在 if 语句中使用类别的深度作为条件来实现这样的效果:

如果类别为深度 2(苹果>大),请执行此操作

else 如果类别为深度 3 (banana>var1>small),则执行其他操作。

我尝试使用此处的函数,但除了空数组之外无法取回任何东西! http://www.devdevote.com/cms/wordpress-hacks/get_depth.html

【问题讨论】:

    标签: php wordpress loops if-statement woocommerce


    【解决方案1】:

    您可以在返回的项目上使用get_ancestors(),然后使用count()。从那里将是简单的逻辑。

    作为一个函数,它看起来像:

    function so50409656_count_ancestors( $object_id, $object_type ='', $resource_type='' ) {
    
        $terms = get_ancestors( $object_id, $object_type, $resource_type );
    
        return count($terms) + 1;
    
    }
    

    然后这样调用:

    $term_depth = so50409656_count_ancestors( $term->term_id, 'your_term_type', 'taxonomy' );
    
    if ( $term_depth === 1 ) :
        // ..your top level ancestor action
    elseif ( $term_depth === 2 ) :
        // ..your direct child choice of actions here
    elseif ( $term_depth === 3 ) :
        // ..your second level child action here
    endif;
    

    编辑:

    澄清了 1 的结果将是顶级祖先,根据 OP 请求,large(在 apple>large 中)等于 2

    【讨论】:

    • 我觉得你需要count($terms) + 1
    • @Reigel - 你当然可以,但它似乎是任意的。在我的示例中,顶级祖先只会返回 0 而不是 1。只要您与顶级祖先将返回的内容的定义保持一致,这并不重要。
    • 好吧,我没有测试过代码,但也许你是对的。是什么让我得出结论,banana>var1>small 将返回 2?并且 OP 期望它作为第 3 部?或者我只是对变量$term_depth 感到困惑。但我明白你的意思.. 干杯!
    • 我的印象是“水果”是一个父术语,但如果 OP 澄清我可以改变它:)
    • 抱歉回复延迟! @Reigel 是正确的,我希望香蕉>var1>small 的值或深度为 3
    【解决方案2】:

    你可以使用下面的递归函数

    function hierarchical_product_cat($category = 0)
    {
        $result = '';
        $args = array('parent' => $category);
        $next = get_terms('product_cat', $args);
    
        if ($next) {
            $result .= '<ul>';
            foreach ($next as $cat) {
                $result .= '<li><a href="' . get_term_link($cat->slug, $cat->taxonomy) . '" title="'.$cat->name.'" ' . '>' . $cat->name . ' (' . $cat->count . ')' . '</a>';
                $result .= $cat->term_id !== 0 ? hierarchical_product_cat($cat->term_id) : null;
            }
            $result .= '</li>';
            $result .= '</ul>';
        }
        return $result;
    }
    echo hierarchical_product_cat();
    

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 2023-02-06
      • 2016-09-07
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 2020-11-06
      • 2012-01-16
      相关资源
      最近更新 更多